<?php
/**
 * Ecars
 * @Version 1.0
 * @Date 2018-10-23
 * @Author 金刚
 * @Email  784892496@qq.com
 * @Phone 13066700403
 * @UpdateTime
 * @Context 登陆控制器
 */
/**
 * @access public
 * @param $id 分类id
 * @return array id和数量
 * @context 获得赠品名称以及类型
 */
function getGivingType($type, $giving_id)
{
    $_array = array();
    if ($type == 2) {
        $type = "服务";
        $title = \think\Db::table('service')->field('service_title')->where(array('id' => $giving_id))->find();
        $title = $title['service_title'];
    } elseif ($type == 1) {
        $type = "商品";
        $title = \think\Db::table('biz_pro')->field('biz_pro_title')->where(array('id' => $giving_id))->find();
        $title = $title ['biz_pro_title'];
    } elseif ($type == 3) {
        $type = "卡券";
        $title = \think\Db::table('card_voucher')->field('card_title')->where(array('id' => $giving_id))->find();
        $title = $title['card_title'];
    } elseif ($type == 4) {
        $type = "积分";
        $title = '积分';
    } else {
        $type = "余额";
        $title = '余额';
    }
    $_array['type'] = $type;
    $_array['title'] = $title;
    return $_array;

}

/**
 * @access public
 * @param null
 * @return
 * @context 评论最大时长
 */
function getsCommentTime()
{
    return 3;
}

/**
 * @access public
 * @param $station 工位id
 * @return 商品比率
 * @context 商品提成比率
 */
function bizproDecude($station, $mark)
{
    if (!empty($station)) {
        $biz_deduct = \think\Db::table("station")->field("biz_deduct,service_deduct")->where(array("id" => $station))->find();
        if (!empty($biz_deduct)) {
            if ($mark == 1) {
                # 商品提成
                return floatval($biz_deduct['biz_deduct']);
            } else {
                # 服务提成
                return floatval($biz_deduct['service_deduct']);
            }
        } else {
            return 0;
        }
    } else {
        return 0;
    }

}

/**
 * @access public
 * @param null
 * @return string
 * @context 结算日期
 */
function getsNode()
{
    return "02";
}

/**
 * @access public
 * @param null
 * @return
 * @context 员工工资标准
 */
function employeeSalaryStandard()
{
    return array(
        "probation" => 0.8, # 试用期工资比率
        "full_salary" => 300, # 满勤工资
        "subsidy" => 100,      # 补助工资
    );
}

function getsNowMonthSalary()
{
    $is_add = \think\Db::table('salary')->field('employee_id')->where("date_format(salary_time,'%Y-%m')='" . date('Y-m') . "'")->select();
    if (empty($is_add)) {
        $where = "";
        $is_exec = true;
    } else {
        # 查询当前在职员工数量
        $in_job = \think\Db::query("select id from employee where employee_status != 0");
        if (!empty($in_job)) {
            # 当前在职员工数组
            $_injob_id = array();
            foreach ($in_job as $v) {
                array_push($_injob_id, $v['id']);
            }
            # 薪资表中员工数组
            $_salary_id = array();
            foreach ($is_add as $v) {
                array_push($_salary_id, $v['employee_id']);
            }
            # 计算两个数组差值
            $diff = array_diff($_injob_id, $_salary_id);
            if (!empty($diff)) {
                $str = null;
                foreach ($diff as $d) {
                    if (is_null($str)) {
                        $str = $d;
                    } else {
                        $str .= "," . $d;
                    }
                }
                $where = " and e.id in (" . $str . ")";
                $is_exec = true;
            } else {
                $is_exec = false;
            }
        }
    }
    if ($is_exec) {
        # 查询所有在职员工
        $employee = \think\Db::query("select e.*,basic_salary,positive_salary,trial_full,formal_full
                                from employee as e
                                left join employee_mapping as em on em.employee_id = e.id
                                where e.employee_status != 0 and date_format(e.employee_create,'%Y-%m') <= '" . date("Y-m", time()) . "' " . $where);
        $_insertArr = array();
        foreach ($employee as $k => $v) {
            # 员工基本工资
            $basic_salary = floatval($v['positive_salary']);
            # 转正满勤
            $full_salary = floatval($v['formal_full']);
            if ($v['employee_status'] == 1) {
                # 员工试用期工资
                $basic_salary = floatval($v['basic_salary']);
                # 试用期满勤
                $full_salary = floatval($v['trial_full']);
            }
            $salary_time = date("Y-m-d");
            array_push($_insertArr, array("employee_id" => $v['id'], "basic_salary" => $basic_salary,
                "full_salary" => $full_salary, "salary_time" => $salary_time));
        }
        if (!empty($_insertArr)) {
            \think\Db::table('salary')->insertAll($_insertArr);
        }
    }
    return null;
}

/**
 * @access public
 * @param $ordernumber 订单编号
 * @param $order_server_id 工单编号
 * @param $employee_id 员工id
 * @param $mark 操作标识 1:添加或者2:修改
 * @param $comment 好评比率 5：5星好评 4：较好 3 ：普通 2 ：差评
 * @param $order_server_type 服务或商品标识 1：商品 2 服务
 * @param $station 工位id
 * @return bool
 * @context 提成添加
 */
function getsDeduct($employee_number, $ordernumber, $order_server_id, $order_server_type, $employee_id, $mark, $comment = 4, $station = '')
{
    if ($employee_number == 0) {
        return false;
    }
    $percent = \think\Db::table('station')->field('service_deduct,custom_service_deduct,biz_deduct,custom_pro_deduct')
        ->where(array('id' => $station))
        ->find();
    # 服务工单
    if ($order_server_type == 2) {
        # 查询服务工单服务id  以及价格
        $order_server = \think\Db::table('order_server os')
            ->field("os.server_id,os.price,os.custommark,os.coupon_mark,o.biz_id,station_id")
            ->join('orders o', 'o.order_number=os.order_number', 'left')
            ->where(array('os.id' => $order_server_id))
            ->find();
        # 如果工单被卡券核销 让价格为0
        /*  if ($order_server['coupon_mark'] == 2) {
              $price = 0;
              $order_server['price'] = 0;
          } else {
              $price = floatval($order_server['price']);
          }*/
        $price = floatval($order_server['price']);
        if ($order_server['custommark'] == 1) {
            # 系统服务
            $server_minprice = \think\Db::table('service_biz sb')
                ->field("service_minprice")
                ->where(array('sb.service_id' => $order_server['server_id'], 'sb.biz_id' => $order_server['biz_id']))
                ->find();
            if (!empty($server_minprice)) {
                if (floatval($order_server['price']) < floatval($server_minprice['service_minprice'])) {
                    $price = floatval($server_minprice['service_minprice']);
                }
            } else {
                # 查询服务本身的最低价格
                $serviceInfo = \think\Db::table('service')->field('service_minprice')->where(array('id' => $order_server['server_id']))->value('service_minprice');
                if (!empty($serviceInfo)) {
                    if (floatval($order_server['price']) < floatval($serviceInfo)) {
                        $price = $serviceInfo;
                    } else {
                        $price = floatval($order_server['price']);
                    }
                }
            }
            /* # 查询服务对应的提成比例
             $percent = \think\Db::table('service_biz sb')
                 ->field('pg.group_percent')
                 ->join('payment_group pg', 'sb.payment_mark=pg.group_mark', 'left')
                 ->where(array('sb.biz_id' => $order_server['biz_id'], 'sb.service_id' => $order_server['server_id']))
                 ->find();*/
            if (!empty($percent['service_deduct'])) {
                $deduct = floatval($percent['service_deduct']) / 100 / intval($employee_number);
            } else {
                $service_deduct = \think\Db::table('service')->field('service_commission')->where(array('id' => $order_server['server_id']))->value('service_commission');
                $deduct = floatval($service_deduct) / 100 / intval($employee_number);
            }
        } else {
            # 自定义服务
            $deduct = floatval($percent['custom_service_deduct']) / 100 / intval($employee_number);
//            $deduct = floatval(bizproDecude($station, 2)) / 100 / intval($employee_number);
        }
    } else {
        # 商品工单
        $order_bizpro = \think\Db::table("order_biz")
            ->field('biz_pro_id,pro_price,coupon_mark,coupon_number,coupon_price,custommark')
            ->where(array('id' => $order_server_id))
            ->find();
        # 查询商品对应的提成比例
        if (!empty($station)) {
            if ($order_bizpro['custommark'] == 1) {
                #系统商品
                $deduct = floatval($percent['biz_deduct']) / 100 / intval($employee_number);
            } else {
                # 自定义商品
                $deduct = floatval($percent['custom_pro_deduct']) / 100 / intval($employee_number);
            }
        } else {
            $deduct = 0;
        }
        $price = floatval($order_bizpro['pro_price']) - floatval($order_bizpro['coupon_price']);
        /*if ($order_bizpro[0]['coupon_mark'] == 2) {
            $price = 0;
        }*/
    }
    # 好评率 默认中评
    if ($comment == 5) {
        $comment_percent = 1;
    } elseif ($comment == 4 or $comment == 3) {
        $comment_percent = 0.5;
    } else {
        $comment_percent = 0;
    }
    if ($order_server_type == 2) {
        $orderdeduct = $price * $deduct * floatval($comment_percent);
    } else {
        $orderdeduct = $price * $deduct * floatval($comment_percent);
    }
    // $orderdeduct = $price * $deduct * floatval($comment_percent);
    # 进行添加操作
    if ($mark == 1) {
        $result = \think\Db::table("deduct")->insert(array(
            "order_number" => $ordernumber,
            'order_server_id' => $order_server_id,
            'type' => $order_server_type,
            'employee_id' => $employee_id,
            'deduct' => getsPriceFormat($orderdeduct),
            'create' => date("Y-m-d H:i:s")
        ));
    } else {
        $deduct_id = \think\Db::table("deduct")->field('id,exec_update')
            ->where(array("order_number" => $ordernumber, 'order_server_id' => $order_server_id, 'employee_id' => $employee_id, 'refer_mark' => 1))
            ->find();
        if ($deduct_id['exec_update'] == 1) {
            $result = \think\Db::table("deduct")->where(array('id' => $deduct_id['id']))->update(array('deduct' => number_format($orderdeduct, 2)));
        } else {
            $result = true;
        }
    }
    if (empty($result)) {
        return true;
    } else {
        return false;
    }
}

/**
 * @access public
 * @param $employee_id 员工id
 * @param $starttime 开始时间
 * @param $endtime 结束时间
 * @return bool
 * @context 获取员工提成
 */
function getsEmployeeDeduct($employee_id, $time, $mark = true)
{
    if ($mark) {
        $_where = "`deduct` > 0";
    } else {
        $_where = '`deduct` < 0';
    }
    $deduct = \think\Db::table('deduct')
        ->where(array('employee_id' => $employee_id))
        ->where("date_format(`create`,'%Y-%m') = '" . $time . "'")
        ->where($_where)
        ->sum('deduct');
    return $deduct;
}

/**
 * @access public
 * @param int $authority_team_mark权限组id
 * @return array 权限id集合
 * @context 获取权限方法
 */
function getAuthorityId($authority_team_mark)
{
    # 通过权限组id查询权限id集合
    if (!empty($authority_team_mark)) {
        $result = \think\Db::table('user_authority_team')
            ->field(array('authority_team_title', 'authority_set'))
            ->where(array('authority_mark' => $authority_team_mark, 'authority_team_status' => 1))
            ->select();
        if (!empty($result[0]['authority_set'])) {
            return $result[0];
        } else {
            return null;
        }
    }
}

function li($active)
{
    $_uri = $_SERVER["REQUEST_URI"];
    $_uri = explode("/", $_uri);
    if ($active === $_uri[2]) {
        return "<div class=\"pointer\">
                <div class=\"arrow\"></div>
                <div class=\"arrow_border\"></div>
            </div>";
    } else {
        return null;
    }

}

function active($active)
{
    $_uri = $_SERVER["REQUEST_URI"];
    $_uri = explode("/", $_uri);
    if ($active === $_uri[2]) {
        return "class=\"active\"";
    } else {
        return null;
    }
}

function a($active)
{
    $_uri = $_SERVER["REQUEST_URI"];
    $_uri = explode("/", $_uri);
    if ($active === $_uri[2]) {
        return "style=\"display:block\"";
    } else {
        return "style=\"display:none\"";
    }
}


/**
 * @access public
 * @param $type 支付方式类型
 * @return 支付方式名称
 * @context 获得支付方式
 */
function getPayType($type)
{
    if (!is_null($type)) {
        switch ($type) {
            case 1:
                return '微信支付';

                break;
            case 2:
                return '支付宝支付';
                break;
            case 3:
                return '银联支付';
                break;
            case 4:
                return '现金支付';
                break;
            case 5:
                return '余额支付';
                break;
            case 6:
                return '卡券支付';
                break;
            case 7:
                return '积分兑换';
                break;
        }
    }
}


/**
 * @access public
 * @param $station_id 工位id
 * @return null
 * @context 获得工位名称
 */
function getStationTitle($station_id)
{
    $station = \think\Db::table('station')->field('station_title')->where(array('id' => intval($station_id)))->select();
    return $station[0]['station_title'];
}

/**
 * @access public
 * @param $id 工单id
 * @return null
 * @context 获得车牌号
 */
function getCarLicensL($id)
{
    if (!empty($id)) {
        $carLicens = \think\Db::query("select mc.car_licens from order_server as os,orders as o,member_car as mc
                                      where os.id = " . $id . " and o.order_number = os.order_number and o.member_car_id = mc.id");
        if (!empty($carLicens)) {
            return $carLicens[0]['car_licens'];
        }
    }

}

/**
 * @access public
 * @param $status 状态编号
 * @return null
 * @context 工单状态
 */
function getOrderServerStatus($status)
{
    if (!empty($status)) {
        switch ($status) {
            case 1:
                return '未开始';
                break;
            case 2:
                return '服务中';
                break;
            case 3:
                return '已完成';
                break;
            case 4:
                return '已结算';
                break;
            case 5:
                return '等待中';
                break;
        }
    }
}

/**
 * @access public
 * @param $status 状态编号
 * @return null
 * @context 订单商品状态
 */
function getOrderBizStatus($status)
{
    if (!empty($status)) {
        switch ($status) {
            case 1:
                return '未结算';
                break;
            case 2:
                return '已结算';
                break;
            case 3:
                return '已完成';
                break;
        }
    }
}

/**
 * @access public
 * @param $biz_id 服务id
 * @return null
 * @context 获取服务名称
 */
function getServerTitle($biz_id)
{
    if (!empty($biz_id)) {
        $title = \think\Db::table('service')->field('service_title')->where(array('id' => $biz_id))->limit(1)->select();
        return $title[0]['service_title'];
    }
}

/**
 * @access public
 * @param $id 服务id
 * @return null
 * @context 获取自定义服务名称
 */
function getsgetCustomServerTitle($id)
{
    if (!empty($id)) {
        $title = \think\Db::table('customserver')->field(array("custom_server_title"))->where(array('id' => $id))->limit(1)->select();
        return $title[0]['custom_server_title'];
    }
}

/**
 * @access public
 * @param $car_id 服务id
 * @return null
 * @context 获取车牌号
 */
function getCarLicensV($car_id)
{
    if (!empty($car_id)) {
        $car = \think\Db::table('member_car')->field('car_licens')->where(array('id' => $car_id))->limit(1)->select();
        if (!empty($car)) {
            # 查询当前车辆是否绑定会员 or mm.member_level_id = 2
            $bindingInfo = \think\Db::query("select count(mc.id) as num ,(select count(mc.id) from member_car as mc left join member_mapping as mm on mc.member_id = mm.member_id where mc.car_licens = '" . $car[0]['car_licens'] . "' and (mm.member_level_id = 1 ) and mm.member_expiration >= '" . date('Y-m-d') . "') as nums from member_car as mc left join member_mapping as mm on mc.member_id = mm.member_id where mc.car_licens = '" . $car[0]['car_licens'] . "' and mm.member_level_id > 2");
            $num = $bindingInfo[0]['num'] + $bindingInfo[0]['nums'];
            if (!empty($bindingInfo) and intval($num) > 0) {
                return "<text>" . $car[0]['car_licens'] . "</text>";
            } else {
                return "<text style='color: red'>" . $car[0]['car_licens'] . "</text>";
            }
        }
    }
}

/**
 * @access public
 * @param $car_id 车辆id
 * @return null
 * @context 获取车辆品牌型号
 */
function getCarLogoSort($car_id)
{
    if (!empty($car_id)) {
        $car = \think\Db::query("select cs.sort_title,cl.title from member_car as mc
                                      left join car_sort as cs on mc.car_type_id = cs.id 
                                      left join car_logo as cl on cl.id = cs.logo_id
                                      where mc.id = " . $car_id);
        if (!empty($car)) {
            $str = $car[0]['title'] . "--" . $car[0]['sort_title'];
            return $str;
        }
    }
}

/**
 * @access public
 * @param $car_id 车辆id
 * @return null
 * @context 获取车辆类型
 */
function getCarType($car_id)
{
    if (!empty($car_id)) {
        $car = \think\Db::query("select cl.level_title from member_car as mc
                                      left join car_sort as cs on mc.car_type_id = cs.id 
                                      left join car_level as cl on cl.id = cs.level
                                      where mc.id = " . $car_id);
        if (!empty($car)) {
            return $car[0]['level_title'];
        }
    }
}

/**
 * @param $biz 商户id
 * @return null|string 生成订单号接口
 */
function getOrderNumber($biz)
{
    $str = null;
    $biz_mark = "30";
    if ($biz >= 10) {
        $biz_mark .= $biz;
    } else {
        $biz_mark .= "3" . $biz;
    }
    # 从redis中获取
    $redis = new \Redis\Redis();
    $number = $redis->get('orderNum' . $biz_mark);
    if (empty($number))
        $number = 0;
    $number = sprintf("%05d", $number + 1);
    $time = strtotime(date("Y-m-d 23:59:59")) - time();
    $redis->set('orderNum' . $biz_mark, $number, $time);
    $str = date("YmdHis") . $biz_mark . $number;
    return $str;
}

/**
 * @access public
 * @param $biz_id 商户id
 * @param $biz_mark 商户标识
 * @param $biz_type 商品类型
 * @return 订单号
 * @context 生成商品订单号接口
 */
function getProOrderNumber($biz, $biz_mark, $biz_type)
{
    $str = null;
    $biz_mark = "3031";
    # 日期时间
    $date = date("YmdHis", time());
    $number = \think\Db::table('orders')->field('id')->where("biz_id = " . $biz . " and order_create >= '" . date('Y-m-d 00:00:01', time()) . "' and order_create <= '" . date('Y-m-d 23:59:59', time()) . "'")->count();
    $number = sprintf("%05d", $number + 1);
    $str = $date . $biz_mark . $number;
    return $str;
}

function test()
{
    $redis = Redis('redis');
    var_dump($redis->hash()->listing('serverList')->value());
    var_dump($redis->hash()->listing(1)->value());
    var_dump($redis->hash()->listing('1')->value());
    var_dump($redis->hash()->listing('2')->value());
    var_dump($redis->hash()->listing('3')->value());
    var_dump($redis->hash()->listing('4')->value());
    var_dump($redis->hash()->listing('5')->value());
    var_dump($redis->hash()->listing('6')->value());
    var_dump($redis->hash()->listing('7')->value());
    var_dump($redis->hash()->listing('8')->value());
    var_dump($redis->hash()->listing('9')->value());
    var_dump($redis->hash()->listing('10')->value());
    var_dump($redis->hash()->listing('11')->value());
    var_dump($redis->hash()->listing('12')->value());
}

//test();
/**
 * @access public
 * @param $order_number 订单编号
 * @return null
 * @context 删除服务列表
 */
function deletKeyServerList()
{
    /* $redis=Redis('redis');
     $redis->key()->del('serverList');
     $redis->key()->del('1');
     $redis->key()->del('2');
     $redis->key()->del('3');
     $redis->key()->del('4');
     $redis->key()->del('5');
     $redis->key()->del('6');
     $redis->key()->del('7');
     $redis->key()->del('8');
     $redis->key()->del('9');
     $redis->key()->del('10');
     $redis->key()->del('11');
     $redis->key()->del('12');*/
    $redis = Redis('redis');
    $station = \think\Db::table('station')->select();
    foreach ($station as $k => $v) {
        $redis->hash()->del($v['service_class_id'], $v['id']);
    }
    $redis->key()->del("serverList");
}

//deletKeyServerList();
function tests($biz_id)
{
    $redis = Redis('redis');
    $station = \think\Db::table('station')->where(array('biz_id' => $biz_id))->select();
    foreach ($station as $k => $v) {
        $redis->hash()->create($v['service_class_id'], $v['id'], null);
    }
    //Redis('redis')->hash()->create('serverList',null,null);
}

//tests(1);
/**
 * @access public
 * @return null
 * @context 获取公众号access_token
 */
/*function getAccess_token()
{
    $access_token = \think\Db::table('access_token')->find();
    if (empty($access_token)) {
        $access_token = requestAccessToken();
        $add = \think\Db::table('access_token')->insert(array('access_token' => $access_token['access_token'], 'time' => strtotime('+110 minutes')));
        if ($add) {
            return $access_token['access_token'];
        }
    } else {
        if (time() > $access_token['time']) {
            $accessToken = requestAccessToken();
            $add = \think\Db::table('access_token')->where(array('id' => $access_token['id']))->update(array('access_token' => $accessToken['access_token'], 'time' => strtotime('+110 minutes')));
            if ($add) {
                return $accessToken['access_token'];
            }
        } else {
            return $access_token['access_token'];
        }
    }
}*/

/**
 * @access public
 * @return null
 * @context  重新申请公众号access_token
 */
/*function requestAccessToken()
{
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx65ed2042b845dad8&secret=6ba58aac3aa0de72f29450379d035dd7";
    $_curl = new \Protocol\Curl();
    $_receipt = json_decode($_curl->get($url), true);
    if (!empty($_receipt['access_token'])) {
        return $_receipt;
    }
}*/

function getAccess_token()
{
    $access_token = \think\Db::table('access_token')->order('id desc')->find();
    if (empty($access_token['access_token'])) {
        $accessToken = requestAccessToken();
        if (!empty($accessToken)) {
            \think\Db::table('access_token')->insert(array('access_token' => $accessToken['access_token'], 'time' => strtotime('+110 minutes')));
            return $accessToken['access_token'];
        } else {
            return null;
        }
    } else {
        if (time() > $access_token['time']) {
            $accessToken = requestAccessToken();
            if (!empty($accessToken)) {
                \think\Db::table('access_token')->where(array('id' => $access_token['id']))->update(array('access_token' => $accessToken['access_token'], 'time' => strtotime('+110 minutes')));
                return $accessToken['access_token'];
            } else {
                return null;
            }
        } else {
            return $access_token['access_token'];
        }
    }
}

/**
 * @access public
 * @return null
 * @context  重新申请公众号access_token
 */
function requestAccessToken()
{
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx281132202d144816&secret=9e9a552eb147972ac5ebd23e4b5580ff";
    $_curl = new \Protocol\Curl();
    $_receipt = json_decode($_curl->get($url), true);
    if (!empty($_receipt['access_token'])) {
        return $_receipt;
    }
}

/**
 * @access public
 * @return null
 * @context 获取公众号js-sdk jsapi_ticket
 */
function getsJsapiTicket()
{
    $sdk = \think\Db::table("sdk_ticket")->limit(1)->select();
    if (empty($sdk)) {
        $js_sdk = requestJsTicket();
        \think\Db::table('sdk_ticket')->data(array('sdk_ticket' => $js_sdk['ticket'], 'sdk_time' => strtotime("+110 minutes", time())))->insert();
        return $js_sdk['ticket'];
    } else {
        if (time() > $sdk[0]['sdk_ticket']) {
            $js_sdk = requestJsTicket();
            \think\Db::table('sdk_ticket')->data(array('sdk_ticket' => $js_sdk['ticket'], 'sdk_time' => strtotime("+110 minutes", time())))->where("id != 0")->update();
            return $js_sdk['ticket'];
        } else {
            return $sdk[0]["sdk_ticket"];
        }
    }
}

/**
 * @access public
 * @return null
 * @context 重新申请js-sdk jsapi_ticket
 */
function requestJsTicket()
{
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . getAccess_token() . "&type=jsapi";
    $_curl = new \Origin\Kernel\Protocol\Curl();
    $_receipt = json_decode($_curl->get($url), true);
    if (!empty($_receipt)) {
        if ($_receipt['errcode'] == 0 and $_receipt['errmsg'] == 'ok') {
            return $_receipt;
        }
    }
}

/**
 * @access public
 * @return null
 * @context 获取公众号 发放会员卡的令牌 api_ticket
 */
function getsApiTicket()
{
    $sdk = \think\Db::table("api_ticket")->limit(1)->select();
    if (empty($sdk)) {
        $api_sdk = requestApiTicket();
        \think\Db::table('api_ticket')->data(array('api_ticket' => $api_sdk['ticket'], 'api_time' => strtotime("+110 minutes", time())))->insert();
        return $api_sdk['ticket'];
    } else {
        if (time() > $sdk[0]['api_time']) {
            $api_sdk = requestApiTicket();
            \think\Db::table('api_ticket')->data(array('api_ticket' => $api_sdk['ticket'], 'api_time' => strtotime("+110 minutes", time())))->update();
            return $api_sdk['ticket'];
        } else {
            return $sdk[0]["api_ticket"];
        }
    }
}

/**
 * @access public
 * @return null
 * @context 重新申请js-sdk api_ticket 会员卡领取的签名包
 */
function requestApiTicket()
{
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . getAccess_token() . "&type=wx_card";
    $_curl = new \Origin\Kernel\Protocol\Curl();
    $_receipt = json_decode($_curl->get($url), true);
    if (!empty($_receipt)) {
        if ($_receipt['errcode'] == 0 and $_receipt['errmsg'] == 'ok') {
            return $_receipt;
        }
    }
}

/**
 * @access public
 * @return null
 * @context  随机生成6位短信验证码
 */
function randCodes()
{
    #验证码长度
    $length = 6;
    #随机验证码
    $num = str_shuffle(rand(pow(10, ($length - 1)), pow(10, $length) - 1));
    return $num;
}

//var_dump(Redis('redis')->hash()->listing('13066700403')->value());
/**
 * @access public
 * @param $lng 经度
 * @param $lat 纬度
 * @return 解析后详情 为json格式
 * @context 逆地址解析
 */
function getAddressResolution($lng, $lat)
{
    $url = "https://restapi.amap.com/v3/geocode/regeo?key=3f5396b83b7b09cfb811027943f8d7c7&location=$lng,$lat&output=json";
    $_curl = new \Origin\Kernel\Protocol\Curl();
    $result = $_curl->get($url);
    return $result;
}

/**
 * @access public
 * @param $city 城市
 * @return 天气解析后详情 为json格式
 * @context 获取天气以及洗车指数
 */
function weather($city)
{
    $city = substr($city, 0, strrpos($city, '市'));
    # 查询当前城市当天天气情况
    $weather = \think\Db::query("select tw.wash_index,wty.weather,wty.weath_icon,tw.temp from todayweather as tw left join weathtype as wty on tw.wid = wty.wid where tw.city = '" . $city . "' and tw.time = '" . date("Y-m-d", time()) . "'");
    if (empty($weather)) {
        # 没有当天记录 重新申请 并存储
        $cityurl = urlencode($city);
        $url = "http://v.juhe.cn/weather/index?format=2&cityname=$cityurl&key=ad106992918a20e29e3ecf6c1c74678e";
        $_curl = new \Origin\Kernel\Protocol\Curl();
        $result = $_curl->get($url);
        $result = json_decode($result, true);
        if ($result['resultcode'] == '200') {
            $todayweather = \think\Db::table('todayweather')
                ->data(array('city' => $city, 'time' => date('Y-m-d', time()), 'wid' => $result['result']['today']['weather_id']['fa'], 'temp' => $result['result']['today']['temperature'], 'wash_index' => $result['result']['today']['wash_index']))
                ->insert();
            if ($todayweather) {
                Session('cityName', $city);
                Session('temp', $result['result']['today']['temperature']);
                Session('weather', $result['result']['today']['weather']);
                Session('wash_index', $result['result']['today']['wash_index']);
                $weath_icon = \think\Db::table('weathtype')->field(array('weath_icon'))->where(array('wid' => $result['result']['today']['weather_id']['fa']))->select();
                Session('weath_icon', $weath_icon[0]['weath_icon']);
                return array('cityName' => $city, 'weath_icon' => $weath_icon[0]['weath_icon'], 'temp' => $result['result']['today']['temperature'], 'weather' => $result['result']['today']['weather'], 'wash_index' => $result['result']['today']['wash_index']);
            }
        }
    } else {
        # 有记录直接抽取 并返回
        Session('cityName', $city);
        Session('temp', $weather[0]['temp']);
        Session('weather', $weather[0]['weather']);
        Session('wash_index', $weather[0]['wash_index']);
        Session('weath_icon', $weather[0]['weath_icon']);
        return array('cityName' => $city, 'weath_icon' => $weather[0]['weath_icon'], 'temp' => $weather[0]['temp'], 'weather' => $weather[0]['weather'], 'wash_index' => $weather[0]['wash_index']);
    }
}

/**
 * @access public
 * @param $city 城市
 * @return 天气解析后详情 为json格式
 * @context 获取天气类型 只用一次即可
 */
function getWeatherType()
{
    $url = "http://v.juhe.cn/weather/uni?key=006602d1da425eb177938beeb9a5b73c";
    $_curl = new \Origin\Kernel\Protocol\Curl();
    $result = $_curl->get($url);
    $result = json_decode($result, true);
    foreach ($result['result'] as $k => $v) {
        \think\Db::table('weathtype')->data(array('wid' => $v['wid'], 'weather' => $v['weather']))->insert();
    }
    return $result;
}

/**
 * @access public
 * @return 门店信息
 * @context 获取门店信息 暂时获取的是单个门店
 */
function getsBizinfo($lat, $lng, $service_id = '', $limit = "")
{
    $biz_limit = NULL;
    if (!empty($limit)) {
        $biz_limit = " limit {$limit}";
    }
    if (!empty($lat) and !empty($lng)) {
        $where = null;
        if (!empty($service_id)) {
            $where = " and id in (select sb.biz_id from service_biz as sb where sb.service_id = {$service_id})";
        }
        $biz = \think\Db::query("SELECT id,biz_title,biz_address,biz_lat,biz_lon,biz_opening,biz_closing, ROUND(6378.138*2*ASIN(SQRT(POW(SIN(({$lat}*PI()/180-biz_lat*PI()/180)/2),2)+COS({$lat}*PI()/180)*COS(biz_lat*PI()/180)*POW(SIN((({$lng}*PI()/180)-(biz_lon*PI()/180))/2),2))),2) AS distance  
        FROM biz where biz_status=1 {$where} order by distance asc {$biz_limit}");
    } else {
        $biz = \think\Db::query("SELECT id,biz_title,biz_address,biz_lat,biz_lon,biz_opening,biz_closing FROM biz where biz_status=1  order by id asc {$biz_limit}");
    }
    return $biz;
}

/**
 * @access public
 * @param $longitude1 起点经度
 * @param $latitude1 起点纬度
 * @param $longitude12 终点经度
 * @param $latitude2 终点纬度
 * @param $unit 显示公里或米 1 为米 2 为公里
 * @param $decimal 保留位数
 * @return 计算两坐标点距离
 * @context 坐标点距离
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit = 2, $decimal = 2)
{

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI / 180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if ($unit == 2) {
        $distance = ($distance / 1000);
    }
    return round($distance, $decimal);
}

/**
 * @access public
 * @return bool
 * @context 微信支付 线上购买商品支付生成订单号 用户openid+时间戳+随机字符串 并用md5 加密
 */
function getsWxpayOrderNumber($openid)
{
    # 随机6位数
    $min = pow(10, (6 - 1));
    $max = pow(10, 6) - 1;
    $shuff = mt_rand($min, $max);
    $ordernumber = md5($openid . time() . $shuff);
    return $ordernumber;
}

/**
 * @access public
 * @return bool
 * @context 引入积分
 */
function getIntegral()
{
    return include("Integral.cfg.php");
}

/**
 * @access public
 * @return bool
 * @context 获取用户会员状态
 */
function getsMemberLevel()
{
    $member_id = Session("member_id");
    $level = 0;
    $memberinfo = \think\Db::table('member_mapping')->field('member_level_id', 'member_expiration')->where(array('member_id' => $member_id))->limit(1)->select();
    if (!empty($memberinfo)) {
        if ($memberinfo[0]['member_level_id'] != 0) {
            if ($memberinfo[0]['member_expiration'] < date("Y-m-d H:i:s", time())) {
                $level = $memberinfo[0]['member_level_id'];
            }
        }
    }
    return $level;
}

/**
 * @access public
 * @return bool
 * @context 获取服务的服务门店价格（小车价格）
 */
function getsServerprice($service_id)
{
    $discount = \think\Db::table('service_car_mediscount')->field(array('discount'))->where(array('service_id' => $service_id, 'service_type' => 1))->select();
    $_array = array();
    foreach ($discount as $k => $v) {
        array_push($_array, $v['discount']);
    }
    sort($_array);
    //var_dump($_array);
    if (!is_null($_array[0])) {
        return $_array[0];
    } elseif (!is_null($_array[1])) {
        return $_array[1];
    } else {
        return $_array[2];
    }
}

/**
 * @access public
 * @return bool
 * @context 引入预约说明
 */
function getAppoinexplain()
{
    return include("Appoinexplain.cfg.php");
}

/**
 * @access public
 * @return bool
 * @context 拼团活动超时退款
 */
function groupActiveRefund()
{
    $group = \think\Db::query("select * from group_active where group_status = 1 and active_end <= '" . date("Y-m-d H:i:s") . "'");
    if (!empty($group)) {
        $wxrefund = new \Apply\EcarBiz\Controller\Refund();
        $info = getTemplate();
        $template = new \Apply\Common\Method\C();
        foreach ($group as $k => $v) {
            if ($v['pay_type'] == 1) {
                # 微信支付退款
                $result = $wxrefund->wxRefund($v['member_id'], $v['order_number'], $v['price'], $v['price'], "您参加的团购活动已结束，由于人数不足，团购失败");
                if ($result) {
                    $opera = \think\Db::table("group_active")->data(array("group_status" => 4))->where(array("id" => $v['id']))->update();
                }
            } else {
                # 余额支付退款
                $result = $wxrefund->balanceRefund($v['member_id'], $v['price'], $v['price']);
                if ($result) {
                    $opera = \think\Db::table("group_active")->data(array("group_status" => 4))->where(array("id" => $v['id']))->update();
                    if ($opera) {
                        $data = array(
                            'first' => array('value' => "您收到退款" . number_format($v['price'], 2) . "元", 'color' => '#000000'),
                            'keyword1' => array('value' => number_format($v['price'], 2), 'color' => '#000000'),# 退款金额
                            'keyword2' => array('value' => date("Y-m-d H:i:s", time()), 'color' => '#000000'), # 退款时间
                            'remark' => array('value' => $info['balancerefund']['remark'], 'color' => '#000000'),
                        );
                        $openid = \think\Db::table("member")->field(array("member_openid"))->where(array("id" => $v['member_id']))->limit(1)->select();
                        $_receipt = $template->sendTemplate($openid[0]['member_openid'], 'LTRownf0hmhq6Oat9T6X-y-e57sBNowHiBzpyAG40iU', '/Epublic/Mine/memberCore.html', $data);
                    }
                }
            }
        }
        if ($opera) {
            return true;
        } else {
            return false;
        }
    }
}

/*根据车辆品牌id查询名称*/
function getsCarLogoTitle($car_logo_id)
{
    $car_logo = \think\Db::table("car_logo")->field("title")->where(array("id" => $car_logo_id))->limit(1)->select();
    return $car_logo[0]['title'];
}

/*根据车系id 查询车辆系列名称*/
function getsCarSortTitles($car_sort_id)
{
    $car_sort = \think\Db::table("car_sort")->field(array("sort_title"))->where(array("id" => $car_sort_id))->limit(1)->select();
    return $car_sort[0]['sort_title'];
}

function testes()
{
    $redis = Redis('redis');
    //var_dump($redis->hash()->listing("serverList")->value());
    $station = \think\Db::table('station')->select();
    //var_dump($station);
    foreach ($station as $k => $v) {
        //var_dump($redis->hash()->listing($v['service_class_id'])->value());
    }
    //var_dump($redis->hash()->listing(5)->value());
}

/*创建工位列表*/
function makestation($biz_id)
{
    $station = \think\Db::table("station")->where(array('biz_id' => $biz_id))->select();
//    dump($station);
//    dump($biz_id);
//    $redis = Redis("redis");
    $redis = new \Redis\Redis();
    foreach ($station as $k => $v) {
        $redis->hSet('stationlist' . $biz_id, $v['id'], null, strtotime(date("Y-m-d 23:59:59")));
//        $redis->hash()->create("stationlist{$biz_id}", $v['id'], null);
    }
//    $redis->key()->setTSC("stationlist{$biz_id}", strtotime(date("Y-m-d 23:59:59", time())));
    return $redis->hGet("stationlist" . $biz_id);
}

//makestation();
function delstation($biz_id)
{
    $station = \think\Db::table("station")->where(array('biz_id' => $biz_id))->select();
//    $redis = Redis("redis");
    $redis = new \Redis\Redis();
    foreach ($station as $k => $v) {
        $redis->hDel('stationlist' . $biz_id, $v['id']);
//        $redis->hash()->del("stationlist{$biz_id}", $v['id']);
    }
//    $redis->hash()->del("stationlist{$biz_id}", "13");
//    $redis->hash()->del("stationlist{$biz_id}", "14");
//    $redis->hash()->del("stationlist{$biz_id}", "15");
//    $redis->hash()->del("stationlist{$biz_id}", "16");
//    $redis->hash()->del("mark{$biz_id}", "value");
    $redis->hDel('stationlist' . $biz_id, '13');
    $redis->hDel('stationlist' . $biz_id, '14');
    $redis->hDel('stationlist' . $biz_id, '15');
    $redis->hDel('stationlist' . $biz_id, '16');
    $redis->hDel('mark' . $biz_id, 'value');
}

function getsCardVoucherTitle($id)
{
    $title = \think\Db::table("card_voucher")->field(array("card_title"))->where(array("id" => $id))->select();
    return $title[0]['card_title'];
}

# 返回卡券類型(赠送卡券时的类型order_giving)
function getsCardVoucherType($type)
{
    if ($type == 1) {
        return "商品卡券";
    } else {
        return "服务卡券";
    }
}

/**
 * @access public
 * @param $order_number 订单号
 * @return pricecount 订单总金额
 * @context 通过订单号查询总金额
 */
function getsOrderPrice($order_number)
{
    $price = \think\Db::query("select 
                            (select sum(os.price) from order_server as os where os.order_number = '" . $order_number . "' ) as osp,
                            (select sum(ob.pro_price) from order_biz as ob where ob.order_number = '" . $order_number . "') as obp,
                            (select sum(ob.coupon_price) from order_biz as ob where ob.order_number = '{$order_number}' and ob.status = 2 and ob.coupon_mark = 1) as bizcouponcount 
                             from orders as o where o.order_number = '" . $order_number . "'");
    if (!empty($price[0]['osp']) and !is_null($price[0]['osp'])) {
        $osprice = floatval($price[0]['osp']);
    } else {
        $osprice = 0;
    }
    if (!empty($price[0]['obp']) and !is_null($price[0]['obp'])) {
        $obprice = floatval($price[0]['obp']);
    } else {
        $obprice = 0;
    }
    if (isset($obprice) and isset($osprice)) {
        $pricecount = $obprice + $osprice - floatval($price[0]['bizcouponcount']);
        # 判断该订单是否使用了现金抵值券
        $cashCoupon = \think\Db::query("select * from log_cashcoupon where voucher_type != 3 and voucher_type != 4  and voucher_type != 7 and voucher_type != 8 and order_number = '" . $order_number . "' and create_time = '" . date("Y-m-d") . "'");
        if (!empty($cashCoupon)) {
            $redPacketVoucherPriceCount = $cashCoupon[0]['voucher_price'];
            if ($redPacketVoucherPriceCount > 0) {
                if ($cashCoupon[0]['voucher_type'] != 3 and $cashCoupon[0]['voucher_type'] != 7 and $cashCoupon[0]['voucher_type'] != 8)
                    $pricecount = sprintf('%.2f', $pricecount - $redPacketVoucherPriceCount);
            }
        }
        $pricecount = getsPriceFormat($pricecount);
        return $pricecount;
    }
}

/**
 * @access public
 * @param $level_id 会员id
 * @return title 会员名称
 * @context 获取会员名称
 */
function getsMemberLevelTitle($id)
{
    $member_level = \think\Db::table("member_level")->field(array('level_title'))->where(array('id' => $id))->select();
    if (!empty($member_level)) {
        return $member_level[0]['level_title'];
    }
}

/**
 * @access public
 * @param $car_licens 车牌号
 * @return array 车辆信息
 * @context 获取车辆信息
 */
function getsCarInfo($car_licens)
{
    if (!empty($car_licens)) {
        # 查询车辆信息
        $car_info = \think\Db::query("select mc.id,mc.car_type_id,mc.car_mileage,cs.sort_title,cs.logo_id,cs.level,cl.title from member_car as mc 
                                                    left join car_sort as cs on mc.car_type_id = cs.id
                                                    left  join car_logo as cl on cs.logo_id = cl.id 
                                                     where mc.car_licens = '" . $car_licens . "' limit 1");
        if (!empty($car_info)) {
            return $car_info[0];
        } else {
            return null;
        }
    }
}

/**
 * @param $station_id 工位id
 * @return array|bool|mixed|null|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @return 员工id
 * @content 获取工位对应的服务员工
 */
function getsEmployeeId($station_id)
{
    $redis = new \Redis\Redis();
    $employee = $redis->hGetJson('stationEmployee', strval($station_id));
    if (empty($employee)) {
        $employee = \think\Db::table('station_staff')
            ->field('employee_id')
            ->join('employee', 'find_in_set(employee.id,station_staff.employee_id)', 'left')
            ->where(array('station_id' => $station_id))
            ->where("employee.employee_status != 0")
            ->value('employee_id');
        $_expira = strtotime(date('Y-m-d 23:59:59')) - time();
        $redis->hSetJson('stationEmployee', strval($station_id), $employee, $_expira);
    }
    if (!empty($employee)) {
        return $employee;
    } else {
        return null;
    }
}

/**
 * @access public
 * @param $auto_code 用户余额支付授权码
 * @return bool
 * @context 验证用户支付码有效性
 */
function getsPayInfo($auto_code, $member_id)
{
    $mobile = substr($auto_code, 0, strpos($auto_code, "mobile"));
    $code = substr($auto_code, (intval(strpos($auto_code, "mobile")) + 6), 6);
    $timestamp = substr($auto_code, (intval(strpos($auto_code, "valicode")) + 8), strpos($auto_code, "timestamp") - (intval(strpos($auto_code, "valicode")) + 8));
    if (!empty($mobile)) {
        if (!empty($code)) {
            # 查询用户信息
            $memberInfo = \think\Db::table('member')->field('id')->where(array('id' => $member_id, 'member_phone' => $mobile))->find();
            if (empty($memberInfo)) {
                return array("status" => false, "return_code" => 3, "msg" => "请扫描本人付款码");
            }
//            $resdis = new \Redis\Redis();
//            $redis_code = $resdis->hGet($mobile . "pay", 'code');
//            if (!empty($redis_code)) {
//                if ($code == $redis_code) {
            if (strtotime("-1 minutes") < intval($timestamp)) {
                # 扫码有效期内返回
                return array("status" => true, "return_code" => 1, "msg" => "二维码有效");
            } else {
                return array("status" => false, "return_code" => 2, "msg" => "二维码失效");
            }
//                } else {
//                    return array("status" => false, "return_code" => 3, "msg" => "二维码无效");
//                }
//            } else {
//                return array("status" => false, "return_code" => 2, "msg" => "二维码失效");
//            }
        } else {
            return array("status" => false, "return_code" => 4, "msg" => "无法解析验证码");
        }
    } else {
        return array("status" => false, "return_code" => 5, "msg" => "无法解析手机号");
    }
}

/**
 * @access public
 * @param $auto_code 用户密码
 * @param $member_id 用户id
 * @return array
 * @context 用户支付密码验证
 */
function valipaypassword($auto_code, $member_id)
{
    $result = \think\Db::table("member_mapping")->field("id")
        ->where(array("member_paypass" => md5($auto_code), "member_id" => $member_id))->find();
    if (!empty($result)) {
        return array("status" => true);
    } else {
        return array("status" => false, 'msg' => "支付密码错误");
    }
}

/********************************推荐人提成********************************************************************************/
/**
 * @access public
 * @param $employee_number 工单员工数量
 * @param $ordernumber 订单编号
 * @param $order_server_id 工单id
 * @param $order_server_type 工单类型 1 商品 2服务
 * @param $employee_id  员工id
 * @return array
 * @context 推荐人加提成
 */
function getsReferrerDeduct($employee_number, $ordernumber, $order_server_id, $order_server_type, $employee_id, $mark = 1, $comment = 4, $station = '')
{
    if ($employee_number == 0) {
        return false;
    }
    $percent = \think\Db::table('station')->field('recommond_royalty,recommond_custom_pro,recommond_custom_service,recommond_pro_royalty')
        ->where(array('id' => $station))
        ->find();
    if ($order_server_type == 2) {
        # 服务工单查询
        $order_server = \think\Db::table('order_server os')
            ->field('os.server_id,os.price,os.custommark,os.coupon_mark,o.biz_id')
            ->join('orders o', 'o.order_number=os.order_number', 'left')
            ->where(array('os.id' => $order_server_id))
            ->find();
        # 查询服务推荐人提成，以及最低提成价格
        if ($order_server['custommark'] == 1) {
            # 系统服务
            $server_refer = \think\Db::table('service_biz sb')
                ->field('service_refer,service_minprice')
                ->where(array('sb.service_id' => $order_server['server_id'], 'sb.biz_id' => $order_server['biz_id']))
                ->find();
            if (!empty($server_refer['service_refer'])) {
                # 存在最低提成价格
                if (!empty($server_refer['service_minprice'])) {
                    if (floatval($order_server['price']) < floatval($server_refer['service_minprice'])) {
                        # 工单价格小于最低提成价格 价格按照最低来
                        $price = floatval($server_refer['service_minprice']);
                    } else {
                        $price = floatval($order_server['price']);
                    }
                } else {
                    # 不存在最低提成价格
                    # 查询服务本身的最低价格
                    $serviceInfo = \think\Db::table('service')->field('service_minprice')->where(array('id' => $order_server['server_id']))->value('service_minprice');
                    if (floatval($order_server['price']) < floatval($serviceInfo)) {
                        $price = $serviceInfo;
                    } else {
                        $price = floatval($order_server['price']);
                    }
                }
                /* $orderdeduct = $price * $deduct;
                 $orderdeduct = number_format($orderdeduct, 2);*/
            } else {
                # 查询服务本身的最低价格
                $serviceInfo = \think\Db::table('service')->field('service_minprice')->where(array('id' => $order_server['server_id']))->value('service_minprice');
                if (floatval($order_server['price']) < floatval($serviceInfo)) {
                    $price = $serviceInfo;
                } else {
                    $price = floatval($order_server['price']);
                }
            }
            if (!empty($percent['recommond_royalty'])) {
                $deduct = floatval($percent['recommond_royalty']) / 100 / intval($employee_number);
            } else {
                $service_refer = \think\Db::table('service')->field('service_refer')->where(array('id' => $order_server['server_id']))->value('service_refer');
                $deduct = floatval($service_refer) / 100 / intval($employee_number);
            }

        } else {
            # 自定义服务获取提成
            $deduct = floatval($percent['recommond_custom_service']) / 100 / intval($employee_number);
            $price = floatval($order_server['price']);
            /* $orderdeduct = number_format(floatval($order_server[0]['price']) * $deduct, 2);*/
        }
    } else {
        # 商品提成
        $order_biz = \think\Db::table("order_biz")->field('biz_pro_id,pro_price,custommark')->where(array("id" => $order_server_id))->find();
        $price = floatval($order_biz['pro_price']);
        if ($order_biz['custommark'] == 1) {
            # 系统商品
            $deduct = $percent['recommond_pro_royalty'] / 100 / intval($employee_number);
        } else {
            # 自定义商品
            $deduct = $percent['recommond_custom_pro'] / 100 / intval($employee_number);
        }
        /*$orderdeduct = number_format((getsBizProDeduct() / 100 / intval($employee_number)) * (floatval($order_biz[0]['pro_price'])), 2);*/
    }
    # 好评率 默认中评
    if ($comment == 5) {
        $comment_percent = 1;
    } elseif ($comment == 4 or $comment == 3) {
        $comment_percent = 0.5;
    } else {
        $comment_percent = 0;
    }
    if ($order_server_type == 2) {
        $orderdeduct = $price * $deduct * floatval($comment_percent);
    } else {
        $orderdeduct = $price * $deduct * floatval($comment_percent);
    }
    // $orderdeduct = $price * $deduct * floatval($comment_percent);
    if ($mark == 1) {
        if (isset($orderdeduct) and !is_null($orderdeduct) and !empty($orderdeduct) and floatval($orderdeduct) != 0) {
            $result = \think\Db::table("deduct")->insert(array(
                    "order_number" => $ordernumber,
                    'order_server_id' => $order_server_id,
                    'type' => $order_server_type,
                    'employee_id' => $employee_id,
                    'deduct' => getsPriceFormat($orderdeduct),
                    'create' => date("Y-m-d H:i:s"),
                    "refer_mark" => 2)
            );
        } else {
            $deduct_id = \think\Db::table("deduct")->field('id')
                ->where(array("order_number" => $ordernumber, 'order_server_id' => $order_server_id, 'employee_id' => $employee_id, 'refer_mark' => 2))
                ->find();
            $result = \think\Db::table("deduct")->where(array('id' => $deduct_id['id']))->update(array('deduct' => getsPriceFormat($orderdeduct)));
        }
        if ($result) {
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }
}

/**
 * @access public
 * @return sting
 * @context 自定义服务推荐人提成
 */
function getsCustomsServerDeduct()
{
    return 5;
}

/**
 * @access public
 * @return sting
 * @context 商品推荐人提成
 */
function getsBizProDeduct()
{
    return 5;
}

/*
 * @access public
 * @return bool
 * @context 获取自定义服务会员折扣
 * */
function getsCustomServerDescount($member_level_id, $type)
{
    //$type 1商品  2服务
    $level_discount = \think\Db::table('level_discount')->field('discount')->where(array('level_id' => $member_level_id, 'type' => $type))->value('discount');
    return $level_discount;
    /* return array(
         '1' => 1,//初级体验
         '2' => 0.9,//体验卡
         '3' => 0.9,//银卡
         '4' => 0.85,//金卡
         '5' => 0.85,//白金卡
         '6' => 0.8,//如意卡
         '7' => 0.8,//贵宾卡
         '8' => 0.75,//钻石卡
         '9' => 1,//至尊卡
     );*/
}

/*
 * @access public
 * @parma $id  自定义商品id
 * @return bool
 * @context 获取自定义商品名称
 * */
function getCustomsBizProTitle($id)
{
    $title = \think\Db::table("custom_biz")->field(array("custom_biz_title"))->where(array("id" => $id))->select();
    if (!empty($title)) {
        return $title[0]['custom_biz_title'];
    }
}

/*
 * @access public
 * @parma $id  商品id
 * @parma $custommark  自定义商品标识
 * @return string
 * @context 获取系统商品或自定义商品名称
 * */
function getsOrderBizProTitle($id, $custommark)
{
    if ($custommark == 1) {
        $title = \think\Db::table('biz_pro')->field('biz_pro_title')->where(array('id' => $id))->find();
        if (!empty($title)) {
            return $title['biz_pro_title'];
        }
    } else {
        $title = \think\Db::table("custom_biz")->field(array("custom_biz_title"))->where(array("id" => $id))->find();
        if (!empty($title)) {
            return $title['custom_biz_title'];
        }
    }
}

/*
 * @access public
 * @return bool
 * @context 获取自定义商品折扣
 * */
function getsCustomBizDescount()
{
    return array(
        '1' => 1,
        '2' => 1,
        '3' => 0.9,
        '4' => 0.9,
        '5' => 0.85,
        '6' => 0.85,
        '7' => 0.8,
        '8' => 0.8,
        '9' => 1,
    );
}

/*
 * @access public
 * @return bool
 * @context 获取用户关注状态
 * */
function getsSubScribeStatus()
{
    $status = \think\Db::table("member")->field("subscribe")->where(array("id" => Session("member_id")))->select();
    if (!empty($status)) {
        if ($status[0]['subscribe'] == 0) {
            return 0;
        } else {
            return 1;
        }
    }
}

function getsShareIntegral($isvalidate = 1)
{
    if ($isvalidate == 1) {
        # 验证当天分享次数
        $count = \think\Db::query("select count(id) as `count` from log_share where date_format(create,'%Y-%m-%d') = '" . date("Y-m-d") . "' and member_id = " . Session("member_id"));
        if ($count[0]['count'] >= 1) {
            return array("status" => 2, "msg" => "分享次数大于1次");
        } else {
            # 引入积分规则
            $integral = getIntegral();
            # 分享积分
            $share = $integral['share_integral'];
            # 添加分享记录

            # 用户增加积分
            $result = \think\Db::query("SET SQL_SAFE_UPDATES=0;update member_mapping set member_integral=member_integral+" . $share . " where member_id =" . Session("member_id"));
            # 添加积分记录
            \think\Db::table("log_integral")->data(array("member_id" => Session('member_id'), "integral_number" => intval($share), "integral_source" => -2, "integral_type" => 1, "integral_time" => date("Y-m-d H:i:s")))->insert();
            # 添加市场补贴记录
            \think\Db::table("subsidy")
                ->data(array("subsidy_type" => 2, "subsidy_come" => 2, "subsidy_create" => date("Y-m-d H:i:s"), "subsidy_number" => intval($share)))
                ->insert();
            # 发送积分变更模板消息
            $member_integral = \think\Db::table('member_mapping')->field(array('member_integral', 'member_openid'))->where(array('member_id' => Session('member_id')))->select();
            $info = getTemplate();
            $template = new \Apply\Common\Method\C();
            $data = array(
                'first' => array('value' => $info['getsIntegralsuccess']['first'], 'color' => '#000000'),
                'keyword1' => array('value' => "获得" . intval($share) . "积分", 'color' => '#000000'),
                'keyword2' => array('value' => "分享成功", 'color' => '#000000'),
                'keyword3' => array('value' => $member_integral[0]['member_integral'], 'color' => '#000000'),
                'remark' => array('value' => intval($integral['commentShare_integral']) . $info['getsIntegralsuccess']['remark'], 'color' => '#000000'),
            );
            $_receipt = $template->sendTemplate($member_integral[0]['member_openid'], 'SNXNc5sbk3FISD4aflhhT4ANYwfCo-dFDmyQgZ-RprQ', '/Epublic/Mine/MemberCore.html', $data);

        }
    } else {
        # 引入积分规则
        $integral = getIntegral();
        # 分享积分
        $share = $integral['share_integral'];
        # 用户增加积分
        $result = \think\Db::query("SET SQL_SAFE_UPDATES=0;update member_mapping set member_integral=member_integral+" . $share . " where member_id =" . Session("member_id"));
        # 添加积分记录
        \think\Db::table("log_integral")->data(array("member_id" => Session('member_id'), "integral_number" => intval($share), "integral_source" => -2, "integral_type" => 1, "integral_time" => date("Y-m-d H:i:s")))->insert();
        # 添加市场补贴记录
        \think\Db::table("subsidy")
            ->data(array("subsidy_type" => 2, "subsidy_come" => 2, "subsidy_create" => date("Y-m-d H:i:s"), "subsidy_number" => intval($share)))
            ->insert();
        # 发送积分变更模板消息
        $member_integral = \think\Db::table('member_mapping')->field(array('member_integral', 'member_openid'))->where(array('member_id' => Session('member_id')))->select();
        $info = getTemplate();
        $template = new \Apply\Common\Method\C();
        $data = array(
            'first' => array('value' => $info['getsIntegralsuccess']['first'], 'color' => '#000000'),
            'keyword1' => array('value' => "获得" . intval($share) . "积分", 'color' => '#000000'),
            'keyword2' => array('value' => "分享成功", 'color' => '#000000'),
            'keyword3' => array('value' => $member_integral[0]['member_integral'], 'color' => '#000000'),
            'remark' => array('value' => intval($integral['commentShare_integral']) . $info['getsIntegralsuccess']['remark'], 'color' => '#000000'),
        );
        $_receipt = $template->sendTemplate($member_integral[0]['member_openid'], 'SNXNc5sbk3FISD4aflhhT4ANYwfCo-dFDmyQgZ-RprQ', '/Epublic/Mine/MemberCore.html', $data);
    }
    if ($result) {
        return array("status" => 1, 'msg' => $share);
    }
}

/*
 * @access public
 * @param $id 消费渠道类型
 * @return bool
 * @context
 * */
function getsconsump_type($id)
{
    switch ($id) {
        case 1:
            return "线上支付";
            break;
        case 2:
            return "门店支付";
            break;
    }
}

/*
 * @access public
 * @param $price 价格
 * @return bool
 * @context 价格格式化
 * */
function getsPriceFormat($price)
{
    return sprintf("%.2f", $price);
}
function getsNumFormat($num)
{
    return sprintf("%.2f",substr(sprintf("%.4f", $num), 0, -2));
}

/**
 * @access public
 * @return null
 * @context 商品或服务名称
 */
function getActiveTitle($type, $id)
{
    if ($type == 1) {
        $title = \think\Db::table('biz_pro')->field('biz_pro_title')->where(array('id' => $id))->select();
        if (!empty($title[0])) {
            return array('title' => $title[0]['biz_pro_title'], 'type' => '商品');
        }
    } elseif ($type == 2) {
        $title = \think\Db::table('service')->field('service_title')->where(array('id' => $id))->select();
        if (!empty($title[0])) {
            return array('title' => $title[0]['service_title'], 'type' => '服务');
        }
    } elseif ($type == 3) {
        return array('title' => '赠送积分', 'type' => '积分');
    } elseif ($type == 4) {
        return array("title" => '赠送余额', 'type' => '余额');
    }

}

/**
 * @access public
 * @return null
 * @context 门店预约订单数量、店内人数、服务等待数量
 */
function BizOrderInfo()
{
    $biz_id = Session("biz_id");
    # 预约订单数量
    $appointorders = \think\Db::query("select count(id) as counts from orders
                                      where order_type = 3 
                                      and (order_status = 1 or order_status = 2 or order_status = 3) 
                                      and biz_id = " . $biz_id);
# 店内人数
    $bizCustom = \think\Db::query("select order_number,
                                          (select count(id) from orders 
                                          where id != 0 and (order_type = 2 or order_type = 3)
                                           and order_create >= '" . date("Y-m-d 00:00:01") . "' 
                                          and order_create <= '" . date("Y-m-d 23:59:59") . "'
                                           and (order_status = 6 or order_status = 5) and biz_id = " . $biz_id . "  ) as num 
                                    from orders where id != 0 and (order_type = 2 or order_type = 3)
                                           and order_status = 6 and biz_id = " . $biz_id);
# 等待数量
    $_orderserver = 0;
    $_custom = 0;
    if (!empty($bizCustom)) {
        $_custom = $bizCustom[0]["num"];
        $_count = 0;
        foreach ($bizCustom as $v) {
            $num = \think\Db::query("select status  from order_server where order_number = " . $v['order_number']);
            if (!empty($num)) {
                foreach ($num as $nv) {
                    if ($nv['status'] != 1) {
                        $_is_status = false;
                        break;
                    } else {
                        $_is_status = true;
                    }
                }
                if ($_is_status == true) {
                    $_count++;
                }
            } else {
                $_count++;
            }
        }
        $_orderserver = $_orderserver + $_count;
    }
# 待打印订单数量
    $list = \think\Db::table("orders")->where(array("order_status" => 7))->count();
    return array("appoint" => $appointorders[0]['counts'], 'bizcustom' => $_custom, "order_servers" => $_orderserver, "readyprint" => $list);
}

/**
 * @access public
 * @return null
 * @context 门店添加车辆密码
 */
function bizCarPassword($bizId)
{
    # 查询门店操作密码
    $_info = \think\Db::table('biz')->field('pwd')->where(array('id' => $bizId))->select();
    return $_info[0]['pwd'];
}

/**
 * @access public
 * @param $server_id 服务id
 * @param $custommark 自定义服务标识
 * @return null
 * @context 获取服务名称
 */
function getsServerOrCustomsTitle($server_id, $custommark)
{
    if ($custommark == 1) {
        # 正常服务
        $title = \think\Db::table('service')->field('service_title')->where(array('id' => $server_id))->limit(1)->find();
        return $title['service_title'];
    } else {
        # 自定义服务
        $title = \think\Db::table('customserver')->field(array("custom_server_title"))->where(array('id' => $server_id))->limit(1)->find();
        return $title['custom_server_title'];
    }

}

/**
 * @access public
 * @return array
 * @context 获取保养类型
 */
function getsMaintainType()
{
    return include("MaintainType.cfg.php");
}

/**
 * @access public
 * @param id 主键
 * @return array
 * @context 获取保养类型名称、公里数、价格
 */
function getsMaintainTypeInfo($id)
{
    if ($id < 0) {
        $type = \think\Db::table('service_log')->field('log_title title')->where(array('id' => -$id))->find();
        return $type;
    } else {
        $type = getsMaintainType();
        return $type[$id];
    }
}


/**
 * @access public
 * @param $type 主键
 * @return array
 * @context 获取保养类型名称
 */
function getsMaintainTypeTitle($type)
{
    $res = getsMaintainType();
    return $res[$type]['title'];
}

/**
 * @access public
 * @param $station_id 工位id集合
 * @return array
 * @context 获取销售额奖金工位名称
 */
function checkSaleroomEmployee($station_id)
{
    $station = \think\Db::query("select station_title from station where id in ($station_id)");
    $str = null;
    foreach ($station as $v) {
        if (is_null($str)) {
            $str = $v['station_title'];
        } else {
            $str .= "<br />" . $v['station_title'];
        }
    }
    return $str;
}

/**
 * @access public
 * @param $employee_id 员工id
 * @return array
 * @context 获取員工姓名
 */
function employeeName($employee_id)
{
    $employee = \think\Db::table("employee")->field(array("employee_name"))->where(array("id" => $employee_id))->limit(1)->select();
    if (!empty($employee[0]['employee_name'])) {
        return $employee[0]['employee_name'];
    }
}

/**
 * @access public
 * @param $employee_id 员工id
 * @param $date 奖金时间 为 Y-m 格式
 * @return array
 * @context 员工奖金
 */
function getsEmployeeBonus($employee_id, $date)
{

    # 查询员工是否又提成
    $bonus = \think\Db::table("saleroom")->where(array("employee_id" => $employee_id))->order(array("saleprice" => "desc"))->select();
    $status = 0;
    if (!empty($bonus)) {
        # 员工存在奖金提成
        $station_income = getsStationBizIncome($date, $bonus[0]['biz_id']);// 获取门店所有工位收入
        foreach ($bonus as $v) {
            $station_id = explode(",", $v['station_id']);
            $price = 0;
            foreach ($station_id as $sid) {
                $price = $price + $station_income[$sid];
            }
            if ($price >= $v['saleprice']) {
                $status = 2; // 达成销售额
                $bonus_id = $v['id'];
                $employee_bonus = $v['bonus'];
                break;
            } else {
                # 所有销售额均未达成
                $status = 3;
            }
        }
        if ($status == 2) {
            $_array = array("status" => $status, "bonus_id" => $bonus_id, "employee_bonus" => $employee_bonus);
        } else {
            $_array = array("status" => 3);
        }
    } else {
        # 员工不存在奖金提成
        $_array = array("status" => 1);
    }
    return $_array;
}

/**
 * @access public
 * @return array
 * @context 引入门店月工位收入
 */
function getsIncludeStationIncome($biz_id)
{
    $file = "StationIncome" . $biz_id . ".php";
    $path = APP_PATH . "stationIncome/" . $file;
    if (file_exists($path)) {
        return include($path);
    } else {
        $array = "<?php return array();";
        file_put_contents($path, $array);
        return include($path);
    }
}

/**
 * @access public
 * @return array
 * @context 月工位收入
 */
function getsStationBizIncome($date, $biz_id)
{
    # 改变时间格式
    $dates = date("Ym", strtotime($date));
    $info = getsIncludeStationIncome($biz_id);
    if (!empty($info[$dates])) {
        return $info[$dates];
    } else {
        # 查询门店工位
        $station = \think\Db::query("select id from station where biz_id = " . $biz_id);
        if (!empty($station)) {
            foreach ($station as $v) {
                # 计算工位收入
                $income = \think\Db::query("select convert(coalesce(sum(price),0),decimal(10,2)) as income from station_income where station_id = {$v['id']} 
and date_format(income_time,'%Y-%m') = '{$date}'");
                $info[$dates][$v['id']] = $income[0]['income'];
            }
            $file = "StationIncome" . $biz_id . ".php";
            $path = APP_PATH . "stationIncome/" . $file;
            $str = "<?php  return " . var_export($info, true) . ";";
            file_put_contents($path, $str, LOCK_EX);
            $mk = getsIncludeStationIncome($biz_id);
            return $mk[$dates];
        }
    }
}

/**
 * @access public
 * @return array
 * @context 获取商品子分类
 */
function getsBizProChildClass($p_class, $str = null)
{
    if (is_null($str)) {
        $str = $p_class;
    }
    $childclass = \think\Db::query("select id from pro_class where class_id = {$p_class}");
    if (!empty($childclass)) {
        foreach ($childclass as $v) {
            $str .= "," . $v['id'];
            getsBizProChildClass($v['id'], $str);
        }
        return $str;
    } else {
        return $str;
    }
}

/**
 * @access public
 * @param $type 类型
 * @return string
 * @context 获取消息类型
 */
function getsNewsType($type)
{
    switch ($type) {
        case 1:
            return "群发消息";
            break;
        case 2:
            return "个人消息";
            break;
        default:
            return "其他类型";
            break;
    }
}

/**
 * @return bool
 * @context 每月1号更新员工状态 薪资调整
 */
function changeEmployeeStatus()
{
    # 判断当前日期是否为本月1号
    if (date("d") == "01") {
        # 查询redis中是否已经改变过员工状态
        $redis = new \Redis\Redis();
        $ischange = $redis->hGet("changeEmployee", "ischange");
        if (empty($ischange)) {
            # 未改变开始查询所有试用期员工和转正工资
            $employee = \think\Db::query("select e.id,e.employee_hugh,em.positive_salary from employee as e,employee_mapping as em where e.id = em.employee_id and e.employee_status =1 and em.employee_positive = '" . date("Y-m-d") . "'");
            if (!empty($employee)) {
                # 查询是否已经添加过月休状态
                $hugh = \think\Db::table("employee_hugh")->where("date_format(nowmonth,'%Y-%m')='" . date("Y-m") . "'")->select();
                $is_hugh = false;
                if (empty($hugh)) {
                    $is_hugh = true;
                }
                foreach ($employee as $v) {
                    # 修改员工状态
                    $alter = \think\Db::table("employee")->data(array("employee_status" => 2))->where(array("id" => $v['id']))->update();
                    if ($alter) {
                        # 查询本月工资表是否已经添加过这个员工
                        $salary = \think\Db::query("select id,basic_salary from salary where date_format(salary_time,'%Y-%m')='" . date("Y-m") . "' and employee_id = {$v['id']}");
                        if (!empty($salary)) {
                            # 如果录入的工资不是转正之后的基本工资 修改
                            if (floatval($salary[0]['basic_salary']) != floatval($v['positive_salary'])) {
                                \think\Db::table("salary")->data(array("basic_salary" => $v['positive_salary']))->where(array("id" => $salary[0]['id']))->update();
                            }
                        }
                    }
                    if ($is_hugh) {
                        # 查询上个月可以休息天数
                        $lasthugh = \think\Db::table("employee_hugh")->field(array("hugh_num"))->where("date_format(nowmonth,'%Y-%m')=
                        '" . date("Y-m", strtotime("-1 month")) . "' and employee_id = " . $v['id'])->select();
                        $attend = 0;  // 上月未出勤天数
                        if (!empty($lasthugh)) {
                            # 查询上月未出勤天数
                            $attend = \think\Db::table("log_attendance")->where("employee_id=" . $v['id'] . " 
                            and  date_format(create_time,'%Y-%m')='" . date("Y-m", strtotime("-1 day")) . "'")->count();
                            # 剩余出勤天数
                            $diff = intval($lasthugh[0]['hugh_num']) - $attend;
                            if ($diff < 0) $diff = 0;
                        } else {
                            $diff = 0;
                        }
                        # 计算本月可以休息多少天
                        $nowhugh = intval($v["employee_hugh"]) + $diff;
                        # 添加记录
                        \think\Db::table("employee_hugh")->data(array(
                            "employee_id" => $v['id'],
                            "hugh_num" => $nowhugh,
                            "nowmonth" => date("Y-m-d"),
                            "hugh_commen" => $v['employee_hugh'],
                            "hugh_lastmonth" => $attend
                        ))->insert();
                    }
                }
            }
            # 添加redis 中已改变状态
            $time = strtotime(date("Y-m-d 23:59:59", time())) - time();
            $redis->hSet("changeEmployee", "ischange", "1", $time);

        }
    }
    return true;
}

/**
 * @context 获取员工工资是否可以使用基本工资加满勤
 */
function getsEmployeebasic($employee_id, $basic, $full, $month)
{
    $time = date("Y-m", strtotime($month));
    # 获取当月有多少天
    $days = date("t", strtotime($month));

    # 获取员工月休情况
    $hugh = \think\Db::table("employee_hugh")->where(" employee_id={$employee_id} and date_format(nowmonth,'%Y-%m')='" . $time . "'")->find();
    # 查询当月未出勤天数
    $attend_select = \think\Db::table("log_attendance")->where("employee_id=" . $employee_id . " 
                            and  date_format(create_time,'%Y-%m')='" . $time . "'")->order(array("create_time" => "asc"))->select();
    $_attend_array = array();
    if (!empty($attend_select)) {
        $attend = count($attend_select);
        # 将未出勤时间放进数组
        foreach ($attend_select as $v) {
            array_push($_attend_array, $v['create_time']);
        }
    } else {
        $attend = 0;
    }
    # 查询该员工状态入职时间是否为本月之前
    $employee_status = \think\Db::table("employee e")
        ->join('employee_mapping em', 'em.employee_id=e.id')
        ->field("e.id,employee_status,employee_create,employee_update,employee_hugh,employee_positive,positive_salary,formal_full")
        ->where(array("e.id" => $employee_id))->find();
    # 判断是否转正
    if ($time >= date('Y-m', strtotime($employee_status['employee_positive']))) {
        # 时间大于转正时间,就是转正
        $basic = $employee_status['positive_salary'];
        $full = $employee_status['formal_full'];
    }
    if ($time != date("Y-m")) {
        # 如果不是当前月
        if (!empty($hugh)) {
            if ($employee_status['employee_status'] != 0) {
                # 在职状态  是否为当月入职
                if ($employee_status['employee_create'] <= $month) {
                    # 判断出勤情况是否符合规定
                    if ($attend <= $hugh['hugh_num']) {
                        $pract_att_days = $days - $attend;// 实际出勤天数
                        # 全勤奖加满勤
                        $salary = getsPriceFormat(floatval($basic) + floatval($full));
                        # 实际基本工资
                        $pract_basic = getsPriceFormat(floatval($basic));
                        # 实际满勤工资
                        $pract_full = floatval($full);
                        # 本月可休息天数
                        $hugh_num = $hugh['hugh_num'];
                        if (!empty($_attend_array)) {
                            # 员工是否连休3天及以上
                            $iscontinus = WhetherDateContinus($_attend_array);
                            if ($iscontinus) {
                                # 连续休3天
                                $salary = getsPriceFormat(floatval($basic));
                                # 实际基本工资
                                $pract_basic = getsPriceFormat(floatval($basic));
                                # 实际满勤工资
                                $pract_full = 0;
                            }
                        }
                    } else {
                        # 无满勤 基本工资按照实际出勤天数算
                        # 计算平均日工资(按照当月天数 - 正常休息天数=实际应出勤天数)
                        $be_att = $days - intval($employee_status['employee_hugh']);
                        $pract_att_days = $days - $attend;// 实际出勤天数
                        if ($pract_att_days >= $be_att) {
                            $salary = getsPriceFormat(floatval($basic));
                        } else {
                            $day_salary = floatval($basic) / $days;
                            $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
                        }
                        # 实际基本工资
                        $pract_basic = $salary;
                        # 实际满勤工资
                        $pract_full = 0;
                        # 本月可休息天数
                        $hugh_num = $hugh['hugh_num'];
                    }
                } else {
                    # 不是当月1号之前入职（按天算）无满勤
                    $be_att = $days - intval($employee_status['employee_hugh']);
                    $pract_att_days = $days - intval(date("d", strtotime($employee_status['employee_create']))) + 1 - $attend;
                    if ($pract_att_days < 0) {
                        $pract_att_days = 0;
                    }
                    # 实际满勤工资
                    $pract_full = 0;
                    if ($pract_att_days >= $be_att) {
                        $salary = getsPriceFormat(floatval($basic));
                    } else {
                        $day_salary = floatval($basic) / $days;
                        $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
                    }
                    # 实际基本工资
                    $pract_basic = $salary;
                    # 本月可休息天数
                    $hugh_num = $hugh['hugh_num'];
                }
            } else {
                # 离职状态
                # 是否为本月离职
                if (date("Y-m", strtotime($employee_status['employee_update'])) != $time) {
                    # 不是本月离职
                    # 为离职状态(说明没有记录)，实际出勤天数为本月天数 - 未出勤天数
                    if ($attend <= $hugh['hugh_num']) {
                        $pract_att_days = $days - $attend;// 实际出勤天数
                        # 全勤奖加满勤
                        $salary = getsPriceFormat(floatval($basic) + floatval($full));
                        # 实际基本工资
                        $pract_basic = getsPriceFormat(floatval($basic));
                        # 实际满勤工资
                        $pract_full = floatval($full);
                        # 本月可休息天数
                        $hugh_num = $hugh['hugh_num'];
                        if (!empty($_attend_array)) {
                            # 员工是否连休3天及以上
                            $iscontinus = WhetherDateContinus($_attend_array);
                            if ($iscontinus) {
                                # 连续休3天
                                $salary = getsPriceFormat(floatval($basic));
                                # 实际基本工资
                                $pract_basic = getsPriceFormat(floatval($basic));
                                # 实际满勤工资
                                $pract_full = 0;
                            }
                        }
                    } else {
                        # 无满勤 基本工资按照实际出勤天数算
                        # 计算平均日工资(按照当月天数 - 正常休息天数=实际应出勤天数)
                        $be_att = $days - intval($employee_status['employee_hugh']);
                        $pract_att_days = $days - $attend;
                        if ($pract_att_days < 0) {
                            $pract_att_days = 0;
                        }
                        # 实际满勤工资
                        $pract_full = 0;
                        if ($pract_att_days >= $be_att) {
                            $salary = getsPriceFormat(floatval($basic));
                        } else {
                            $day_salary = floatval($basic) / $days;
                            $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
                        }
                        # 实际基本工资
                        $pract_basic = $salary;
                        # 本月可休息天数
                        $hugh_num = $hugh['hugh_num'];
                    }
                } else {
                    # 本月离职
                    # 无满勤 基本工资按照实际出勤天数算
                    # 计算平均日工资(按照当月天数 - 正常休息天数=实际应出勤天数)
                    $be_att = $days - intval($employee_status['employee_hugh']);
                    $pract_att_days = intval(date("d", strtotime($employee_status['employee_update']))) - 1 - $attend;
                    if ($pract_att_days < 0) {
                        $pract_att_days = 0;
                    }
                    # 实际满勤工资
                    $pract_full = 0;
                    if ($pract_att_days >= $be_att) {
                        $salary = getsPriceFormat(floatval($basic));
                    } else {
                        $day_salary = floatval($basic) / $days;
                        $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
                    }
                    # 实际基本工资
                    $pract_basic = $salary;
                    # 本月可休息天数
                    $hugh_num = $hugh['hugh_num'];
                }
            }
        } else {
            if ($employee_status['employee_status'] != 0) {
                # 在职状态  是否为当月入职
                if ($employee_status['employee_create'] <= $month) {
                    # 为当前月1号之前入职(说明没有记录)，实际出勤天数为本月天数 - 未出勤天数
                    if ($attend <= $employee_status['employee_hugh']) {
                        $pract_att_days = $days - $attend;// 实际出勤天数
                        # 全勤奖加满勤
                        $salary = getsPriceFormat(floatval($basic) + floatval($full));
                        # 实际基本工资
                        $pract_basic = getsPriceFormat(floatval($basic));
                        # 实际满勤工资
                        $pract_full = floatval($full);
                        # 本月可休息天数
                        $hugh_num = $employee_status['employee_hugh'];
                        if (!empty($_attend_array)) {
                            # 员工是否连休3天及以上
                            $iscontinus = WhetherDateContinus($_attend_array);
                            if ($iscontinus) {
                                # 连续休3天
                                $salary = getsPriceFormat(floatval($basic));
                                # 实际基本工资
                                $pract_basic = getsPriceFormat(floatval($basic));
                                # 实际满勤工资
                                $pract_full = 0;
                            }
                        }
                    } else {
                        # 无满勤 基本工资按照实际出勤天数算
                        # 计算平均日工资(按照当月天数 - 正常休息天数=实际应出勤天数)
                        $be_att = $days - intval($employee_status['employee_hugh']);
                        $pract_att_days = $days - $attend;
                        # 实际满勤工资
                        $pract_full = 0;
                        if ($pract_att_days >= $be_att) {
                            $salary = getsPriceFormat(floatval($basic));
                        } else {
                            $day_salary = floatval($basic) / $days;
                            $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
                        }
                        # 实际基本工资
                        $pract_basic = $salary;
                        # 本月可休息天数
                        $hugh_num = $employee_status['employee_hugh'];
                    }
                } else {
                    # 不是当月1号之前入职（按天算）无满勤
                    $be_att = $days - intval($employee_status['employee_hugh']);
                    $pract_att_days = $days - intval(date("d", strtotime($employee_status['employee_create']))) + 1 - $attend;
                    if ($pract_att_days < 0) {
                        $pract_att_days = 0;
                    }
                    # 实际满勤工资
                    $pract_full = 0;
                    if ($pract_att_days >= $be_att) {
                        $salary = getsPriceFormat(floatval($basic));
                    } else {
                        $day_salary = floatval($basic) / $days;
                        $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
                    }
                    # 实际基本工资
                    $pract_basic = $salary;
                    # 本月可休息天数
                    $hugh_num = $employee_status['employee_hugh'];
                }
            } else {
                # 离职状态
                # 是否为本月离职
                if (date("Y-m", strtotime($employee_status['employee_update'])) != $time) {
                    # 不是本月离职
                    # 为离职状态(说明没有记录)，实际出勤天数为本月天数 - 未出勤天数
                    if ($attend <= $employee_status['employee_hugh']) {
                        $pract_att_days = $days - $attend;// 实际出勤天数
                        # 全勤奖加满勤
                        $salary = getsPriceFormat(floatval($basic) + floatval($full));
                        # 实际基本工资
                        $pract_basic = getsPriceFormat(floatval($basic));
                        # 实际满勤工资
                        $pract_full = floatval($full);
                        # 本月可休息天数
                        $hugh_num = $employee_status['employee_hugh'];
                        if (!empty($_attend_array)) {
                            # 员工是否连休3天及以上
                            $iscontinus = WhetherDateContinus($_attend_array);
                            if ($iscontinus) {
                                # 连续休3天
                                $salary = getsPriceFormat(floatval($basic));
                                # 实际基本工资
                                $pract_basic = getsPriceFormat(floatval($basic));
                                # 实际满勤工资
                                $pract_full = 0;
                            }
                        }
                    } else {
                        # 无满勤 基本工资按照实际出勤天数算
                        # 计算平均日工资(按照当月天数 - 正常休息天数=实际应出勤天数)
                        $be_att = $days - intval($employee_status['employee_hugh']);
                        $pract_att_days = $days - $attend;
                        if ($pract_att_days < 0) {
                            $pract_att_days = 0;
                        }
                        # 实际满勤工资
                        $pract_full = 0;
                        if ($pract_att_days >= $be_att) {
                            $salary = getsPriceFormat(floatval($basic));
                        } else {
                            $day_salary = floatval($basic) / $days;
                            $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
                        }
                        # 实际基本工资
                        $pract_basic = $salary;
                        # 本月可休息天数
                        $hugh_num = $employee_status['employee_hugh'];
                    }
                } else {
                    # 是本月离职
                    # 无满勤 基本工资按照实际出勤天数算
                    # 计算平均日工资(按照当月天数 - 正常休息天数=实际应出勤天数)
                    $be_att = $days - intval($employee_status['employee_hugh']);
                    $pract_att_days = intval(date("d", strtotime($employee_status['employee_update']))) - 1 - $attend;
                    if ($pract_att_days < 0) {
                        $pract_att_days = 0;
                    }
                    # 实际满勤工资
                    $pract_full = 0;
                    if ($pract_att_days >= $be_att) {
                        $salary = getsPriceFormat(floatval($basic));
                    } else {
                        $day_salary = floatval($basic) / $days;
                        $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
                    }
                    # 实际基本工资
                    $pract_basic = $salary;

                    # 本月可休息天数
                    $hugh_num = $employee_status['employee_hugh'];
                }
            }

        }
    } else {
        # 本月可休息天数
        $hugh_num = $hugh['hugh_num'];
        if (empty($hugh_num)) {
            $hugh_num = $employee_status['employee_hugh'];
        }
        # 计算平均日工资(按照当月天数 - 正常休息天数=实际应出勤天数)
        $be_att = $days - intval($hugh['hugh_num']);
        # 当前月在职状态判断
        if ($employee_status['employee_status'] != 0) {
            $pract_att_days = intval(date("d")) - $attend;
        } else {
            $pract_att_days = intval(date("d", strtotime($employee_status['employee_update']))) - $attend;
        }
        # 实际满勤工资
        $pract_full = 0;
        if ($pract_att_days >= $be_att) {
            $salary_basic = getsPriceFormat(floatval($basic));
            $salary = getsPriceFormat(floatval($basic) + floatval($full));
            # 实际满勤工资
            $pract_full = floatval($full);
        } else {
            $day_salary = floatval($basic) / $days;
            $salary = getsPriceFormat(floatval($day_salary) * $pract_att_days);
            $salary_basic = $salary;
        }
        # 实际基本工资
        $pract_basic = $salary_basic;
    }
    return array("salary" => $salary, "pract_basic" => $pract_basic, "pract_full" => $pract_full,
        "attend" => $attend, "hugh_num" => $hugh_num, "pract_att_days" => $pract_att_days);
}

/**
 * @param $date_array
 * @return bool
 * @context 员工未出勤是否连续3天
 */
function WhetherDateContinus($date_array)
{
    if (!empty($date_array)) {
        if (count($date_array) >= 3) {
            $mark = 1;// 连续状态
            for ($i = 0; $i < count($date_array) - 1; $i++) {
                if ($mark == 3) {
                    return true;
                    break;
                } else {
                    $head = strtotime($date_array[$i]);
                    $foot = strtotime($date_array[$i + 1]);
                    if (($foot - $head) == 3600 * 24) {
                        $mark += 1;
                    } else {
                        $mark = 1;
                    }
                }
            }
            if ($mark != 3) {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
 * @return array
 * @context 会员卡背景图
 */
function wxCardBg()
{
    return array(
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmLLxPeU6gOW2zYpeV2klQNdfIVgqOvricIj4YVEa2tueicNHbDq4xTS6uw/0",
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmLnpk7iaGv5bRrJj0bZaicTty9GqaCPI5kRRibdiaCkeXY0H2cjH38qq7rgA/0",
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmL6l9ImwTgP5cNeNnb2iaiaficePeWEdeVxqYZXc4crto8790m2I8hnh6jw/0",
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmLZ1JouSnEibQ2xzHUBJYbwGmbdSh7yt6wQaKhkicmwlE8pKrXoXcVzmvg/0",
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmLebjgaicAZqhGTUnOQXOUbG2NF59ibOBjag9n4K5BiaVKwjHL62sdJmtcg/0",
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmLKndnCsPLPV8b3jaduLHmKEl8Kh5Xib2TSt5uFdxFxtoOQWKoCoFlLrQ/0",
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmLQAUoaTXrHzmGPfGTNYU76x3bqmcFzicVkAicHzX5sWysRJqx7gp8rKsA/0",
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmLt5doRY7pvNAtI8wK6iaLPsjJFJ2TFgVF8ibkIJoKmFQwicribOfjAGnFpg/0",
        "http://mmbiz.qpic.cn/mmbiz_png/QqODknfYoGdM5iaJIQ6JtS6ObT2BBYCmLHoibemkH0KnQYebYWCDPzOH4Lgw24hXP0kluus5Gyrem0ra6dXeaJDQ/0",
    );
}

/*
 * @context 获取会员卡背景图
 * */
function getsWxCardBg($level)
{
    $card = wxCardBg();
    return $card[$level];
}

/**
 * @return array
 * @context 会员名称
 */
function wxleveltitle()
{
    return array(
        "普通卡",
        "120天初级体验",
        "300天体验卡",
        "银色Vip",
        "黄金Vip",
        "白金Vip",
        "如意Vip",
        "贵宾Vip",
        "钻石Vip",
        "至尊Vip",
    );
}

/**
 * @param $level
 * @return 获取会员等级名称
 */
function getsWxLevelTitle($level)
{
    $title = wxleveltitle();
    return $title[$level];
}

/**
 * @param $mark
 * @return null
 * @context 通过标识查询提成名称比例
 */
function getsPayment($mark)
{
    $_return = Session('getsPaymentInfo' . $mark);
    if (empty($_return)) {
        if (!empty($mark)) {
            # 查询提成名称及比例
            $payment = \think\Db::table("payment_group")->field(array("group_title", "group_percent"))->where(array("group_mark" => $mark))->select();
            if (!empty($payment)) {
                $_return = $payment[0]['group_title'] . "&nbsp;&nbsp;&nbsp;&nbsp;" . getsPriceFormat($payment[0]['group_percent']) . "%";
            } else {
                $_return = null;
            }
        } else {
            $_return = null;
        }
        Session('getsPaymentInfo' . $mark, $_return);
    }
    return $_return;
}

/**
 * @return float
 * @context 会员退卡折价费用
 */
function chargesfee()
{
    return 0.2;
}

/**
 * @return string
 * @context 退卡密码
 */
function passWordSystem($bizId)
{
    # 查询门店操作密码
    $_info = \think\Db::table('biz')->field('pwd')->where(array('id' => $bizId))->select();
    return $_info[0]['pwd'];
}

/**
 * @access public
 * @param $stauts 支付方式编号
 * @return 支付方式名称
 * @context 获得办理会员卡支付方式
 */
function getHandlePayType($type)
{
    if (!is_null($type)) {
        switch ($type) {
            case 1:
                return '微信支付';

                break;
            case 2:
                return '支付宝支付';
                break;
            case 3:
                return '现金支付';
                break;
            case 4:
                return '银联支付';
                break;
        }
    }
}

/**
 * @param $biz_id
 * @param $employee_id
 * @param $star
 * @param $order_id
 * @return bool
 * @context 添加评论分数
 */
function createEvaluationScore($biz_id, $employee_id, $star, $order_id, $reffermark)
{
    if ($star == 5) {
        $score = 5;
    } elseif ($star == 4 or $star == 3) {
        $score = 3;
    } else {
        $score = 0;
    }
    $res = \think\Db::table("evaluation_score")->data(array(
        "order_id" => $order_id,
        "employee_id" => $employee_id,
        "create_time" => date("Y-m-d H:i:s"),
        "score" => $score,
        "evalua_level" => $star,
        "biz_id" => $biz_id,
        "reffermark" => $reffermark
    ))->insert();
    if ($res) {
        return true;
    } else {
        return false;
    }
}

function aaa()
{
    $a = \think\Db::table("order_evaluation")->select();
    ignore_user_abort(true);     // 忽略客户端断开
    set_time_limit(0);           // 设置执行不超时
    $str = null;
    foreach ($a as $v) {
        if (!empty($v['staff_id'])) {
            $employee_id = explode(",", $v['staff_id']);
            foreach ($employee_id as $e) {
                if ($v['quality_staff'] == 5) {
                    $score = 5;
                } elseif ($v['quality_staff'] == 4 or $v['quality_staff'] == 3) {
                    $score = 3;
                } else {
                    $score = 0;
                }
                if (is_null($str)) {
                    $str .= "(" . $v['order_id'] . "," . $e . ",'" . $v['evaluation_create'] . "'," . $score . "," . $v['quality_staff'] . "," . $v['store_id'] . "," . "1" . ")";
                } else {
                    $str .= ",(" . $v['order_id'] . "," . $e . ",'" . $v['evaluation_create'] . "'," . $score . "," . $v['quality_staff'] . "," . $v['store_id'] . "," . "1" . ")";
                }

            }
        }

    }
    $res = \think\Db::query("insert into evaluation_score(order_id,employee_id,create_time,
                                            score,evalua_level,biz_id,reffermark) values" . $str);
    return true;
}

/*
 * @context 减少库存
 * */
function decBizInvent($bizpro_id, $num, $biz_id = "")
{
    if (empty($biz_id)) {
        if (empty(Session("biz_id"))) {
            $biz_id = 1;
        } else {
            $biz_id = Session("biz_id");
        }
    }
    # 减少门店库存商品数量
    \think\Db::query("update biz_invent set `number`=`number` - " . $num . " where biz_pro_id = {$bizpro_id}  and biz_id = {$biz_id}");
    return true;
}

/**
 * @param $str
 * @return string
 * @context 字符串价格格式化
 */
function getsStrFormat($str)
{
    if (is_numeric($str)) {
        return getsPriceFormat($str);
    } else {
        return $str;
    }
}

/*
 * @param $type 奖品类型
 * @context 获取奖品类型名称
 * */
function getsPrizeType($type)
{
    switch ($type) {
        case 1:
            return "积分";
            break;
        case 2:
            return "余额";
            break;
        case 3:
            return "卡券";
            break;
        case 4:
            return "红包";
            break;
        case 5:
            return "其他物品";
            break;
        default :
            return null;
    }
}

/*
 * @context 奖品说明
 * */
function PrizeExplain()
{
    return array(
        "integral" => "您获得的积分奖自动计入到您的积分余额中，并可正常使用，请注意查收！",
        "balance" => "您获得及现金余额奖励将自动计入到您的现金余额中，储值余额只限会员使用，请注意查看！",
        "voucher" => "您获得的奖励优惠券将自动存入到您的优惠卡券中，可直接抵用服务使用，请注意查看！",
        "redpack" => "您获得的红包奖励将自动存入到您的优惠卡券中，可直接到店抵用服务或商品，请您注意查收！",
    );
}

/*
 * @context 根据奖品类型获取奖品说明
 * */
function getsPrizeExplain($type)
{
    $explain = PrizeExplain();
    switch ($type) {
        case 1 :
            return $explain['integral'];
        case 2:
            return $explain['balance'];
        case 3:
            return $explain['voucher'];
        case 4:
            return $explain['redpack'];
        default:
            return null;
    }

}

/*
 * @context 获取任务类型
 * */
function getsTaskType($type)
{

    switch ($type) {
        case 1 :
            return "分享";
        case 2:
            return "线上支付";
        case 3:
            return "卡券核销";
        case 4:
            return "查看文章";
        case 5:
            return "推荐好友";
        case 6:
            return "生活超市";
        case 7:
            return "办理会员";
        case 8:
            return "购买商品";
        case 9:
            return "预约服务";
        case 10:
            return "参加活动";
        case 11:
            return "用户评论";
        case 12:
            return "积分兑换";
        default:
            return null;
    }
}

/*
 * @access public
 * @param $member_id
 * @param $task_type 任务类型
 * @context 完成任务条件
 * @return bool
 * */
function finishTask($member_id, $task_type)
{

    if (!empty($member_id)) {
        $task = \think\Db::query("select t.id,t.task_num,lta.task_plan,lta.id as ltid  from task as t,log_task as lta
                              where t.id = lta.task_id and t.task_type = {$task_type} 
                            and t.task_status = 1 and lta.task_status =1 and lta.member_id = {$member_id}");

        if (!empty($task)) {
            foreach ($task as $v) {
                if ($v['task_plan'] < $v['task_num']) {

                    \think\Db::query("update log_task set task_plan= task_plan+1 where id = {$v['ltid']}");
                }
            }
        }
        return true;
    } else {
        return false;
    }
}

function finishTaskCondition($memberId, $taskType)
{
    if (!empty($memberId) and !empty($taskType)) {
        # 查询是否存在未完成的该类型的任务
        $taskInfo = \think\Db::table('member_task mt')
            ->field('mt.id,mt.task_plan,mt.task_total,mt.over_time')
            ->leftJoin('task t', 't.id=mt.task_id')
            ->where(array('t.task_type' => $taskType, 'mt.finish_status' => 1, 'mt.member_id' => $memberId))
            ->select();
        //Db::table('aaa')->insert(array('info'=>json_encode($taskInfo)));
        if (!empty($taskInfo)) {
            $redis = new \Redis\Redis();
            $getui = new \app\service\IGeTuiService();
            $getuiState = false;
            foreach ($taskInfo as $k => $v) {
                if (!empty($v['over_time'])) {
                    if ($v['over_time'] < date('Y-m-d H:i:s')) {
                        # 未完成,修改状态
                        \think\Db::table('member_task')->where(array('id' => $v['id']))->update(array('finish_status' => 4));
                    } else {
                        //Db::table('aaa')->insert(array('info'=>'你大爷','type'=>$v['id']));
                        goto finishContinue;
                    }
                } else {
                    //Db::table('aaa')->insert(array('info'=>'你二大爷','type'=>$v['id']));
                    finishContinue:
                    //Db::table('aaa')->insert(array('info'=>'你三大爷','type'=>$v['id']));
                    $completeNum = $v['task_plan'] + 1;
                    if ($taskType == 17) {
                        # 连续签到
                        $completeNum = $redis->hGet('memberSignNum', $memberId);
                        if (empty($completeNum)) {
                            $completeNum = 0;
                        }
                    }

                    if ($completeNum >= $v['task_total']) {
                        # 已完成,修改状态
                        $getuiState = true;
                        $_arr = array('task_plan' => $completeNum, 'finish_status' => 2, 'finish_time' => date("Y-m-d H:i:s"));
                    } else {
                        $_arr = array('task_plan' => $completeNum);
                    }
                    //Db::table('aaa')->insert(array('info'=>json_encode($_arr),'type'=>$v['id']));
                    \think\Db::table('member_task')->where(array('id' => $v['id']))->update($_arr);
                }
            }
            if ($getuiState) {
                # 发送领取任务奖励通知
                $getui->pushMessageToSingle('任务提醒', '有可领取的任务奖励,立即领取', $memberId);
            }
            return array('status' => true);
        } else {
            return array('status' => false, 'msg' => '用户任务不存在');
        }
    } else {
        return array('status' => false, 'msg' => '参数存在空值');
    }
}

/*
 * @access public
 * @param $type  类型
 * @context 库存商品类型
 * @return str
 * */
function getsInventType($type)
{
    switch ($type) {
        case 1 :
            return "商城商品";
        case 2:
            return "积分商品";
        case 3:
            return "配件";
        case 4:
            return "耗材";
        default:
            return null;
    }
}

/**
 * Convert a string to an array
 * @param string $str
 * @param number $split_length
 * @return multitype:string
 * @context 字符串无分隔符拆分成数组
 */
function mb_str_splits($str, $split_length = 1, $charset = "UTF-8")
{
    if (func_num_args() == 1) {
        return preg_split('/(?<!^)(?!$)/u', $str);
    }
    if ($split_length < 1) return false;
    $len = mb_strlen($str, $charset);
    $arr = array();
    for ($i = 0; $i < $len; $i += $split_length) {
        $s = mb_substr($str, $i, $split_length, $charset);
        $arr[] = $s;
    }
    return $arr;
}

/*
 * @context 权限标识
 * */
function getsPrivilegeMark()
{
    return array(
        "commen" => "普通特权",
        "lineup" => "免排队特权",
    );
}

function getsPrivilegeMarkTitle($mark)
{
    $_arr = getsPrivilegeMark();
    return $_arr[$mark];
}

/*
 * @access public
 * @param $car_licens 车牌号
 * @context 根据车牌号查询是否具有免排队特权
 * */
function getsLineUp($car_licens, $biz_id)
{
    $lineup = 0;// 免排队特权标识 0 无 1有
    # 先查詢门店是否可以使用免排队权限(不用查询  都支持)
    /* if (!empty($biz_id)) {
         $biztypemark = \think\Db::query("select ifnull(find_in_set(biz.biz_type,
 (select biztypemark from privilege where privilege_mark = 'lineup')),0) as canuse
  from biz where biz.id = {$biz_id}");
         if ($biztypemark[0]['canuse'] == 0) {
             # 不允许该门店使用
             return $lineup;
         }
     }*/
    # 查询该车绑定人id信息
    $membercon = \think\Db::table("member_car")->field("member_id")->where(array("car_licens" => $car_licens, 'queue_status' => 1))->where('member_id != 0 and status != 3')->group(array("member_id"))->select();
    # 车辆绑定总人数
    $carcount = count($membercon);
    if ($carcount > 1) {
        # 查询当前绑定的人是否都不是特权会员情况
        $levelstatus = 0;// 定义是否绑定的人都不是会员
        foreach ($membercon as $k => $v) {
            # 查询用户是否有免排队特权状态  or  mm.member_level_id =2
            $columlineup = \think\Db::query("select id from level_content where find_in_set((select id  from privilege 
                          where title = '免排队'), 
                          (select level_privilege from level_content where level_id = (select 
                                (case 
                                  when (mm.member_level_id =1 ) then 
                                  if(mm.member_expiration>='" . date("Y-m-d") . "',1,0)
                                  when (mm.member_level_id >1 or mm.member_level_id=0) then
                                   member_level_id
                                  end
                                ) as member_level_id
                              from member_mapping as mm where member_id = {$v['member_id']}))) limit 1");
            if (!empty($columlineup)) {
                $levelstatus++;
            }
        }
        if ($levelstatus != 0) {
            if ($levelstatus >= $carcount) {
                # 当前绑定用户全都有免排队特权
                $lineup = 1;
            } else {
                # 至少有一个有免排队特权
                # 查询车牌号绑定的用户是否有免排队权限
                $lastorder = \think\Db::query("select member_id from orders where car_liences = '{$car_licens}' order by id desc limit 1");
                if (!empty($lastorder)) {
                    # 查询这个车这个人是否还是绑定状态
                    $bindstatus = \think\Db::table("member_car")->field("id")->where("member_id = {$lastorder[0]['member_id']} and car_licens='" . $car_licens . "' and status != 3")->select();
                    if (!empty($bindstatus)) {
                        # 查询用户是否有免排队特权 or mm.member_level_id =2
                        $privilege = \think\Db::query("select id from level_content where find_in_set((select id  from privilege 
                          where title = '免排队'), 
                          (select level_privilege from level_content where level_id = (select 
                                (case 
                                  when (mm.member_level_id =1 ) then 
                                  if(mm.member_expiration>='" . date("Y-m-d") . "',1,0)
                                  when mm.member_level_id >1 or mm.member_level_id=0 then
                                   member_level_id
                                  end
                                ) as member_level_id
                              from member_mapping as mm where member_id = {$lastorder[0]['member_id']}))) limit 1");
                        if (!empty($privilege)) {
                            # 存在免排队特权
                            $lineup = 1;
                        }
                    }
                }
            }
        }
        # else当前绑定的用户全都没有免排队特权


    } else {
        if ($carcount == 1) {
            # 查询用户是否有免排队特权 or mm.member_level_id =2
            $privilege = \think\Db::query("select id from level_content where find_in_set((select id  from privilege 
                          where title = '免排队'), 
                          (select level_privilege from level_content where level_id = (select 
                                (case 
                                  when (mm.member_level_id =1 ) then 
                                  if(mm.member_expiration>='" . date("Y-m-d") . "',1,0)
                                  when (mm.member_level_id >1 or mm.member_level_id=0)  then
                                   member_level_id
                                  end
                                ) as member_level_id
                              from member_mapping as mm where member_id in (select member_id from member_car where car_licens='{$car_licens}' and status != 3 and queue_status= 1 and member_id != 0)))) limit 1");
            if (!empty($privilege)) {
                # 存在免排队特权
                $lineup = 1;
            }
        }
    }
    return $lineup;
}

/*
 * @access public
 * @param $member_id 用户id
 * @context 根据用户id查询是否具有免排队特权
 * */
function getsMemberLineUp($member_id)
{
    $lineup = -1;// 免排队特权标识 -1 无 1有
    # 查询用户是否有免排队特权
    $privilege = \think\Db::query("select id from level_content where find_in_set((select id  from privilege 
                          where title = '免排队'), 
                          (select level_privilege from level_content where level_id = (select 
                                (case 
                                  when (mm.member_level_id =1 or mm.member_level_id =2) then 
                                  if(mm.member_expiration>='" . date("Y-m-d") . "',1,0)
                                  when (mm.member_level_id >2 or mm.member_level_id=0)  then
                                   member_level_id
                                  end
                                ) as member_level_id
                              from member_mapping as mm where member_id ={$member_id}))) limit 1");
    if (!empty($privilege)) {
        # 存在免排队特权
        $lineup = 1;
    }
    return $lineup;
}

/*
 * @context 获取门店名称 等信息
 * @param $mark 是否存入缓存标识 存在不存入
 * */
function getsBizInfoArray($biz_id, $mark = '')
{
    if (!empty($mark)) {
        $info = \think\Db::table("biz")->where(array("id" => $biz_id))->find();
        if (!empty($info)) {
            $redis = new \Redis\Redis();
            $redis->hSetJson('bizInfo', strval($biz_id), $info);
        }
        return $info;
    } else {
        $redis = new \Redis\Redis();
        $biz_info = $redis->hGetJson('bizInfo', strval($biz_id));
        if (!empty($biz_info)) {
            return $biz_info;
        } else {
            $info = \think\Db::table("biz")->where(array("id" => $biz_id))->find();
            if (!empty($info)) {
                $redis->hSetJson('bizInfo', strval($biz_id), $info);
                return $info;
            } else {
                return array();
            }
        }
    }
}
